Reputation: 706
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.
Upvotes: 1
Views: 3371
Reputation: 1259
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";
}
Upvotes: 2