Spring REST returning PDF - Response status 406 (not acceptable)

前端 未结 1 1976
太阳男子
太阳男子 2021-02-15 14:16

I read many questions on SO about this type of issue, but all of them recommend using the correct Jackson version. This is my current situation:

REST API:



        
相关标签:
1条回答
  • 2021-02-15 15:01

    Basically there is no need to add produces = "application/pdf" in RequestMapping as it seems to try to convert the ResponeBody internally. You can just add MediaType to response headers which is what you need.

    @ResponseBody
    @RequestMapping(value = "get/pdf/{id}", headers="Accept=*/*", method = RequestMethod.GET)
    public ResponseEntity<InputStreamResource> getPdfContractById(@PathVariable("id") Long id){
            // Get the remove file based on the fileaddress
            RemoteFile remotefile = new RemoteFile(id);
    
            // Set the input stream
            InputStream inputstream = remotefile.getInputStream();
            // asume that it was a PDF file
            HttpHeaders responseHeaders = new HttpHeaders();
            InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
            responseHeaders.setContentLength(contentLengthOfStream);
            responseHeaders.setContentType(MediaType.valueOf("application/pdf"));
            // just in case you need to support browsers
            responseHeaders.put("Content-Disposition", Collections.singletonList("attachment; filename=somefile.pdf"))
            return new ResponseEntity<InputStreamResource> (inputStreamResource,
                                       responseHeaders,
                                       HttpStatus.OK);
    }
    
    0 讨论(0)
提交回复
热议问题