简体   繁体   English

从Java Servlet下载时文件损坏

[英]File corrupted on download from java servlet

I have a process in a servlet that creates a .pdf file and sends it to the client. 我在servlet中有一个创建.pdf文件并将其发送到客户端的进程。 However, Adobe won't open the downloaded file ("There was an error opening this document. The file is damaged and could not be repaired."). 但是,Adobe不会打开下载的文件(“打开此文档时出错。该文件已损坏,无法修复。”)。 The original created file residing on the server is fine and Adobe doesn't have a problem opening it. 驻留在服务器上的原始创建的文件很好,并且Adobe没问题打开它。

My code: 我的代码:

private static void sendFile(HttpServletResponse response, String pdfPath) throws FileNotFoundException, IOException {
    PrintWriter out = response.getWriter();
    File f = new File(pdfPath);

    response.setHeader("Content-Transfer-Encoding", "binary");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + f.getName());
    response.setContentLength((int) f.length());

    response.setContentType("application/pdf");

    FileInputStream fileInputStream = new FileInputStream(pdfPath);

    int i;
    while ((i = fileInputStream.read()) != -1) {
        out.write(i);
    }
    fileInputStream.close();
    out.close();
}

A Writer writes characters , not bytes. Writer写入字符 ,而不是字节。

Use the response output stream . 使用响应输出流

And don't read and write byte by byte, especially from a FileInputStream .This is extremely inefficient. 并且不要逐字节读取和写入,尤其是从FileInputStream读取和写入时,这效率极低。 Just use Files.copy() . 只需使用Files.copy()即可

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM