I have a Spring MVC application, and one of the JSPs must show images coming from a database.
The images are stored in the DB as Blobs.
What is the easiest w
I have compiled some code here!
Please have a look and let me know if that fits your case. I think this should work.
The simplest solution (in terms so writing as less as possible) is a Spring MVC Controller Method with return Type OutputStream or ResponseEntity.
I prefer: return a ResponseEntity:
@RequestMapping(value = "/reportTemplate/{id}/content", method = RequestMethod.GET)
public ResponseEntity<byte[]> downloadReportTemplateContent(
@PathVariable("id") final ReportTemplate reportTemplate)
throws IOException {
ReportDatei file = reportTemplate.getFile();
String fileName = reportTemplate.getName() + EXCEL_FILE_NAME_ENDING;
HttpHeaders responseHeaders = httpHeaderExcelFileAttachment(fileName,
datei.getDaten().length);
return new ResponseEntity<byte[]>(file.getDataArray(),
responseHeaders, HttpStatus.OK);
}
public static HttpHeaders httpHeaderExcelFileAttachment(final String fileName,
final int fileSize) {
String encodedFileName = fileName.replace('"', ' ').replace(' ', '_');
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.parseMediaType("application/vnd.ms-excel"));
responseHeaders.setContentLength(fileSize);
responseHeaders.set("Content-Disposition", "attachment");
responseHeaders.add("Content-Disposition", "filename=\"" + encodedFileName + '\"');
return responseHeaders;
}
But there are many more:
Use HttpServletResponse directly
@RequestMapping(value = "/document/{id}/fileContent", method = RequestMethod.GET)
public void getDocumentFileContent(final HttpServletResponse response,
@PathVariable("id") final Document document)
throws IOException {
FileContentUtil.writeFileContentToHttpResponse(document.getFile(),
response, this.fileService);
}
public static void writeFileContentToHttpResponse(final CommonFileInfo fileInfo,
final HttpServletResponse response,
final FileService fileService) throws IOException {
String mimeType = fileInfo.getMimeType() != null ? fileInfo.getMimeType() : CommonFileInfo.DEFAULT_MIME_TYPE;
String fileName = fileInfo.getOriginalName().replace('"', ' ');
FileContent fileContent = fileService.loadFileContent(fileInfo.getFileContentBusinessId());
response.setContentType(mimeType);
response.setContentLength(fileInfo.getSize());
response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + '"');
response.getOutputStream().write(fileContent.getContent());
response.getOutputStream().flush();
}