1

I have created the code for uploading a pdf file into the BLOB of MySQL database.

HTML Code:

<form method="post" action="doUpload" enctype="multipart/form-data">
    <table border="0">
        <tr>
            <td>Pick file #1:</td>
            <td><input type="file" name="fileUpload" size="50" /></td>
        </tr>
        <tr>
             <td colspan="2" align="center"><input type="submit" value="Upload" /></td>
        </tr>
     </table>
</form>

Spring Controller:

@RequestMapping(value = "/doUpload", method = RequestMethod.POST)
public String handleFileUpload(HttpServletRequest request,
        @RequestParam CommonsMultipartFile[] fileUpload) throws Exception {

    if (fileUpload != null && fileUpload.length > 0) {
        for (CommonsMultipartFile aFile : fileUpload) {
            System.out.println("Saving file: " + aFile.getOriginalFilename());
            UploadFile uploadFile = new UploadFile();
            uploadFile.setFileName(aFile.getOriginalFilename());
            uploadFile.setData(aFile.getBytes());
            fileUploadDao.save(uploadFile);                
        }
    }
    return "Success";
}

I could able to upload the PDF File into the blob field of MySQL table. But I don't know how to retrieve the blob data, as a hyperlink, where I can click the link and download the pdf file. Kindly help me.

1 Answer 1

2

You can try fetching the document content from MySQL and then set the data stream in the response object.

Using a response.setHeader() method to set "Content-Disposition" will launch the Save As dialog in the browser for the user to download the file.

@RequestMapping("/retrieve/{fileName}")
public String download(@PathVariable("fileName")
        String fileName, HttpServletResponse response) {

    DownloadFile downloadDocument = downloadFileDao.get(fileName);
    try {
        response.setHeader("Content-Disposition", "inline; filename=\"" + fileName + "\"");
        OutputStream out = response.getOutputStream();
        response.setContentType(downloadDocument.getContentType());
        IOUtils.copy(downloadDocument.getContent().getBinaryStream(), out);
        out.flush();
        out.close();

    } catch (SQLException e) {
        System.out.println(e.toString());
        //Handle exception here
    } catch (IOException e) {
        System.out.println(e.toString());
        //Handle exception here
    }

    return "Success";
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.