从服务器文件系统中的文件在浏览器中加载PDF



如何获得位于服务器目录结构中的文件中的pdf,以便在浏览器中为Spring MVC应用程序的用户加载?

我在谷歌上搜索了这个,发现了关于如何生成pdf的帖子,但是他们的答案在这种情况下不起作用。例如,这另一个帖子是不相关的,因为res.setContentType("application/pdf");在我的代码下面没有解决问题。此外,这个其他帖子描述了如何从数据库中做到这一点,但没有显示完整的工作控制器代码。其他帖子也有类似的问题,导致它们在这种情况下无法工作。

我需要简单地提供一个文件(不是从数据库),并有它是由用户在他们的浏览器中可见。我想到的最好的是下面的代码,它要求用户下载PDF或在浏览器外的单独应用程序中查看它。我可以对下面的特定代码做哪些具体的更改,以便用户在单击链接时自动在浏览器中看到PDF内容,而不是被提示下载它?

@RequestMapping(value = "/test-pdf")
public void generatePdf(HttpServletRequest req,HttpServletResponse res){
    res.setContentType("application/pdf");
    res.setHeader("Content-Disposition", "attachment;filename=report.pdf");
    ServletOutputStream outStream=null;
    try {
        BufferedInputStream bis = new BufferedInputStream(
                new FileInputStream(new File("/path/to", "nameOfThe.pdf")));
            /*ServletOutputStream*/ outStream = res.getOutputStream();
            //to make it easier to change to 8 or 16 KBs
            int FILE_CHUNK_SIZE = 1024 * 4;
            byte[] chunk = new byte[FILE_CHUNK_SIZE];
            int bytesRead = 0;
            while ((bytesRead = bis.read(chunk)) != -1) {outStream.write(chunk, 0, bytesRead);}
            bis.close();
            outStream.flush();
            outStream.close();
    } 
    catch (Exception e) {e.printStackTrace();}
}

变化

res.setHeader("Content-Disposition", "attachment;filename=report.pdf");

res.setHeader("Content-Disposition", "inline;filename=report.pdf");

你还应该设置内容长度

FileCopyUtils是方便的:

@Controller
public class FileController {
    @RequestMapping("/report")
    void getFile(HttpServletResponse response) throws IOException {
        String fileName = "report.pdf";
        String path = "/path/to/" + 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());
    }
}

最新更新