Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
pdf文件无法';使用ajax无法保存_Ajax_Spring_Pdf_Download_Http Post - Fatal编程技术网

pdf文件无法';使用ajax无法保存

pdf文件无法';使用ajax无法保存,ajax,spring,pdf,download,http-post,Ajax,Spring,Pdf,Download,Http Post,我有这样的rest端点: @PostMapping(value = "/pdf") public ResponseEntity<byte[]> downloadPdf(@RequestBody ReportData reportData) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_PDF); headers.setCacheCo

我有这样的rest端点:

@PostMapping(value = "/pdf")
public ResponseEntity<byte[]> downloadPdf(@RequestBody ReportData reportData) {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_PDF);
    headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
    headers.setContentDispositionFormData(reportData.getFileName(), reportData.getFileName() + ".pdf");

    try {
        byte[] generatedPdf = downloadService.getPdf(reportData.getUrl(), reportData.getParams(), reportData.getReportName());
        return new ResponseEntity<>(generatedPdf, headers, HttpStatus.OK);
    } catch (IOException e) {
        logger.error("Error downloading report.", e);
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
但这只给了我一个空的pdf

如果我用rest客户端点击这个按钮并从那里下载pdf,我可以看到正确的pdf。

我已经更改了ajax请求,如bellow及其工作方式

$.ajax({
        method: 'POST',
        contentType: 'application/json',
        xhrFields: {
                        responseType: 'blob'
                    },
        url: 'api/download/pdf',
        data: JSON.stringify(constructPostData()),
        success: function (result) {
            var link = document.createElement('a');
            link.href = window.URL.createObjectURL(result);
            link.download = reportName;
            link.click();
        },
        error: function (xhr, status) {
            console.log(status);
        }
    });
$.ajax({
        method: 'POST',
        contentType: 'application/json',
        xhrFields: {
                        responseType: 'blob'
                    },
        url: 'api/download/pdf',
        data: JSON.stringify(constructPostData()),
        success: function (result) {
            var link = document.createElement('a');
            link.href = window.URL.createObjectURL(result);
            link.download = reportName;
            link.click();
        },
        error: function (xhr, status) {
            console.log(status);
        }
    });