With Spring 3.0 you can use the `HttpEntity` return object. If you use this, then your controller does not need a `HttpServletResponse` object, and therefore it is easier to test.
*Except this, this answer is relative equals to the one of Infeligo*.
If the return value of your pdf framework is an byte array *(read the second part of my answer for other return values)* :
@RequestMapping(value = "/files/{fileName}", method = RequestMethod.GET)
public HttpEntity<byte[]> createPdf(
@PathVariable("fileName") String fileName) throws IOException {
byte[] documentBody = this.pdfFramework.createPdf(filename);
HttpHeaders header = new HttpHeaders();
header.setContentType(MediaType.APPLICATION_PDF);
header.set(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=" + fileName.replace(" ", "_"));
header.setContentLength(documentBody.length);
return new HttpEntity<byte[]>(documentBody, header);
}
----
**If the return type of your PDF Framework (`documentBbody`) is not already a byte array** (and also no `ByteArrayInputStream`) then it would been wise **NOT** to make it a byte array first. Instead it is better to use:
- [`InputStreamResource`][1],
- [`PathResource`][2] (since Spring 4.0) or
- [`FileSystemResource`][3],
example with `FileSystemResource`:
@RequestMapping(value = "/files/{fileName}", method = RequestMethod.GET)
public HttpEntity<byte[]> createPdf(
@PathVariable("fileName") String fileName) throws IOException {
File document = this.pdfFramework.createPdf(filename);
HttpHeaders header = new HttpHeaders();
header.setContentType(MediaType.APPLICATION_PDF);
header.set(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=" + fileName.replace(" ", "_"));
header.setContentLength(document.length());
return new HttpEntity<byte[]>(new FileSystemResource(document),
header);
}
[1]:
[To see links please register here]
[2]:
[To see links please register here]
[3]:
[To see links please register here]