从spring查看pdf通过react / axios获取请求

时间:2019-07-15 21:13:57

标签: reactjs spring-mvc axios

我有一个spring端点,它充当pdf作为byte [],并且有一个React ui,当我尝试调用该端点时得到406。

弹簧终点:

<script>
$(document).`ready(function(){
    $("`#myBtn").`click(function(){
        $("`#myModal").`modal();
    });
});

我尝试过:

@GetMapping(value = "report/{report_id}", produces = MediaType.APPLICATION_PDF_VALUE)
    public ResponseEntity<InputStreamResource> generateReviewTaskReport(
            HttpServletResponse response,
            @PathVariable("report_id") String reportId,
            @RequestAttribute(USER_ID) String loginId) {

        byte[] report = reportService.generateReport(reportId, loginId);
        ByteArrayInputStream inputStream =  new ByteArrayInputStream(report);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentLength(report.length);
        headers.add("Content-Disposition", "inline;filename=" + reportId + "_report.pdf");

        return ResponseEntity
                .ok()
                .headers(headers)
                .contentType(MediaType.APPLICATION_PDF)
                .body(new InputStreamResource(inputStream));
    }

相同的结果。

反应请求:

headers.add("Content-Disposition", "attachment;filename=" + reportId + "_report.pdf");

我尝试过responseType:'bufferArray',从我的spring端点返回一个普通的byte [],总是得到406。我猜测是因为我的'Accept'标头中的MIME类型错误。我试过'application / pdf'和'* / *',结果相同。我需要什么头来接受InputStreamResource或byte []?

有了邮递员,我可以很好地下载文件。

我的配置:

export const getReport = (reportId = '') => (dispatch) => {
  const report = `${apiConfig.reportUrl}${reportId}`

  const promise = axios.get(report,
     {
        responseType: 'blob',
        headers: {
          'Accept': 'application/pdf'
      }
    })

  return dispatch({
    type: GET_REPORT,
    payload: promise,
  })
}


case GET_REPORT:
      if (payload.data) {
        const report = new Blob([payload.data])
        reportUrl = URL.createObjectURL(report)
        window.open(reportUrl, "_blank")
      }

1 个答案:

答案 0 :(得分:0)

一般的解决方案,但我认为在您的情况下,它应该可以正常工作;)

axios({
  url: 'http://api.dev/file-download', //your url
  method: 'GET',
  responseType: 'blob', // important
}).then((response) => {
   const url = window.URL.createObjectURL(new Blob([response.data]));
   const link = document.createElement('a');
   link.href = url;
   link.setAttribute('download', 'file.pdf'); //or any other extension
   document.body.appendChild(link);
   link.click();
});

要点:https://gist.github.com/javilobo8/097c30a233786be52070986d8cdb1743

满分:https://gist.github.com/javilobo8