【问题标题】:loading a pdf in-browser from a file in the server file system?从服务器文件系统中的文件加载 pdf 在浏览器中?
【发布时间】:2015-09-08 22:08:49
【问题描述】:

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

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

我需要简单地提供一个文件(而不是来自数据库),并让用户在他们的浏览器中查看它。我想出的最好的是下面的代码,它要求用户下载 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();}
}

【问题讨论】:

    标签: spring spring-mvc pdf


    【解决方案1】:

    改变

    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());
    
        }
    }
    

    【讨论】:

    • 谢谢!省去了很多麻烦
    猜你喜欢
    • 2017-02-16
    • 2012-12-06
    • 1970-01-01
    • 2015-06-29
    • 1970-01-01
    • 1970-01-01
    • 2016-04-16
    • 2022-08-10
    • 1970-01-01
    相关资源
    最近更新 更多