Reputation: 1
In my springboot application, I try to return a pdf file with a ResponseEntity-Resource- to mock a service. So I can't change the return type of this method.
My code :
@RequestMapping(
value = "/pdf",
produces = MediaType.APPLICATION_PDF_VALUE,
method = RequestMethod.GET
)
public ResponseEntity<Resource> getpdf() {
try {
ClassPathResource pdfFile = new ClassPathResource("sample.pdf");
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET, POST, PUT");
headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "Content-Type");
headers.add(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate");
headers.add(HttpHeaders.PRAGMA, "no-cache");
headers.add(HttpHeaders.EXPIRES, "0");
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + pdfFile.getFilename());
headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_PDF_VALUE);
log.info("pdfFile.contentLength() : " + pdfFile.contentLength());
return ResponseEntity
.ok()
.headers(headers)
//.contentLength(pdfFile.contentLength())
//.contentType(MediaType.APPLICATION_PDF)
.body(new InputStreamResource(pdfFile.getInputStream()));
} catch (IOException e) {
log.error("Couldn't serialize response for content type ", e);
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
When I try to call this get with postman or swagger I have a 406 with response header :
{
"date": "Fri, 02 Nov 2018 14:04:44 GMT",
"content-length": "0",
"content-type": null
}
Does anyone have an idea?
Upvotes: 0
Views: 19245
Reputation: 31
way too complex.. downloading a file is much more easy
@GetMapping(value="printing/",produces= MediaType.APPLICATION_PDF_VALUE)
public @ResponseBody byte[] print(@RequestParam("filterParam") String filterParam) {
try {
FileInputStream fis= new FileInputStream(new File("path to your file"));
byte[] targetArray = new byte[fis.available()];
fis.read(targetArray);
return targetArray;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
Upvotes: 3
Reputation: 15888
You can remove produces = MediaType.APPLICATION_PDF_VALUE
.
There is no need to add produces = MediaType.APPLICATION_PDF_VALUE,
in RequestMapping as it seems to try to convert the ResponeBody internally.
Below line of code is enough which you are already using.
headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_PDF_VALUE);
Upvotes: 0