如何使用Postman从Spring REST服务下载PDF

时间:2018-12-13 18:15:11

标签: spring-boot postman

我有一个基于Spring的Rest服务,它提供PDF作为响应。使用下面的代码,我可以在邮递员中获取PDF内容作为二进制值。我的问题是在致电服务时将其下载为附件。

要实现此目的,我需要对代码或客户端进行任何更改。

@GetMapping(value="/getUserpdf")
    public ResponseEntity<Resource> getUserInfo(@RequestHeader(name="reqHeader") Map<String, String> reqHeader,
                                                  @RequestParam(name="userId",required=true) String userId){

        MetaInfo metaInfo = getHeaderValues(reqHeader);

        //To get Actual PDF content as Bytes
        byte[] pdfBytes = getUserPdfService.getUserInfo(metaInfo,userId);

        ByteArrayResource resource = new ByteArrayResource(pdfBytes);

        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=UserInfo.pdf");



        return ResponseEntity
                      .ok()
                      .headers(headers)
                      .contentLength(pdfBytes.length)
                      .contentType(MediaType.parseMediaType("application/octet-stream")).body(resource);
    }

我还注册了Converter

@Bean
    public HttpMessageConverters customConverters() {
        ByteArrayHttpMessageConverter arrayHttpMessageConverter = new ByteArrayHttpMessageConverter();
        return new HttpMessageConverters(arrayHttpMessageConverter);
    }

1 个答案:

答案 0 :(得分:1)

这里是一个例子:

@GetMapping("/getUserpdf/{id}")
    @CrossOrigin
    @ResponseBody
    public ResponseEntity<InputStreamResource> downloadFile(@PathVariable(required = true, value = "id") Long id,@RequestParam(name="userId",required=true) String userId,HttpServletRequest request) throws IOException {

        //To get Actual PDF content as Bytes
        byte[] pdfBytes = getUserPdfService.getUserInfo(id,userId);
        if (Objects.nonNull(pdfBytes)) {
            String fileName = "UserInfo.pdf";
            MediaType mediaType = MediaType.parseMediaType("application/pdf");
            File file = new File(fileName);
            FileUtils.writeByteArrayToFile(file, pdfBytes); //org.apache.commons.io.FileUtils
            InputStreamResource resource = new InputStreamResource(new FileInputStream(file));

            return ResponseEntity.ok()
                    // Content-Disposition
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + file.getName())
                    // Content-Type
                    .contentType(mediaType)
                    // Contet-Length
                    .contentLength(file.length()) //
                    .body(resource);
        } else {
            throw ResponseEntity.notFound().build();
        }
    }

注意:我对mediaType不满意,但是您可以确认是否可以!