繁体   English   中英

从Java Servlet下载时文件损坏

[英]File corrupted on download from java servlet

我在servlet中有一个创建.pdf文件并将其发送到客户端的进程。 但是,Adobe不会打开下载的文件(“打开此文档时出错。该文件已损坏,无法修复。”)。 驻留在服务器上的原始创建的文件很好,并且Adobe没问题打开它。

我的代码:

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

Writer写入字符 ,而不是字节。

使用响应输出流

并且不要逐字节读取和写入,尤其是从FileInputStream读取和写入时,这效率极低。 只需使用Files.copy()即可

暂无
暂无

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

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