尝试以 pdf 形式查看数据,pdf 为空白

3 pdf inputstream outputstream reactjs spring-boot

我试图在下一个选项卡中打开 pdf 文件,它打开但始终为空白。我正在从 springboot 中的文件夹中调用 pdf 文件。数据确实显示在控制台日志中。

弹簧代码:

 @RequestMapping(value = "/report", method = RequestMethod.GET)
    void getFile(HttpServletResponse response) throws IOException {

        String fileName = "test123.pdf";
        String path = "TrainingDocuments/SuperPartnerUser/" + fileName;

        File file = new File(path);
        FileInputStream inputStream = new FileInputStream(file);

        response.setContentType("application/pdf");
        response.setContentLength((int) file.length());
        response.setHeader("Content-Disposition", "inline;filename=\"" + fileName + "\"");

        FileCopyUtils.copy(inputStream, response.getOutputStream());

    }
Run Code Online (Sandbox Code Playgroud)

反应代码:

function download(filename, text) {
        var element = document.createElement('a');
        element.setAttribute('href', 'data:application/pdf;charset=utf-8,' + encodeURIComponent(text));
         element.setAttribute('target','_blank');
       
        element.style.display = 'none';
        document.body.appendChild(element);
       
        element.click();
       
        document.body.removeChild(element);
        }

    function test () {
        Api(`tempFileDownload/report`, 'Get',"",3).then((data) => {
            console.log(data);
            download("test",data)
            const file = new Blob([ data ], { type: 'application/pdf' });

            //Build a URL from the file
            const fileURL = URL.createObjectURL(file);
            //Open the URL on new Window
            window.open(fileURL);
        });
}
Run Code Online (Sandbox Code Playgroud)

PDF 数据 空白 PDF

小智 6

问题是前端的 api 调用,后端工作正常;响应类型必须是 blob

const result = await axios({
            url: `${localUrl + url}`, //your url
            method: 'GET',
            responseType: 'blob', // important
        })
        .then(({ data }) => data);
    return result;
Run Code Online (Sandbox Code Playgroud)