java - 文件下载时出错

标签 java excel download

在我的 servlet 中,我使用 cookie 传递文件路径并下载文件,如下所示

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    String b = null;
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
         for (Cookie cookie : cookies) {
           if (cookie.getName().equals("thecookie")) {
               b = cookie.getValue();
            }
          }
        }

    BufferedReader br = new BufferedReader(new FileReader(b+"/logs.txt"));
    String path = br.readLine();
    br.close();

    File file = new File(path+"/Results.xlsx");
    FileInputStream fileIn = new FileInputStream(file);
    ServletOutputStream out = response.getOutputStream();

    byte[] outputByte = new byte[4096];
    //copy binary contect to output stream
    while(fileIn.read(outputByte, 0, 4096) != -1)
    {
        out.write(outputByte, 0, 4096);
    }
    fileIn.close();
    out.flush();
    out.close();
}

一切正常,文件正在下载,但是我想下载Results.xlsx,正在下载的文件是download.zip,这个download.zip 与我的 Results.xlsx 文件大小相同,但 excel 无法打开。

我该如何正确地做到这一点?

最佳答案

您正在将数据写入输出流,但没有设置内容类型或文件名。您应该使用:

response.setHeader("Content-Disposition", "attachment; filename=Result.xslx");
response.setContentType(
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

(在开始写入输出流之前。)

此外,您的流复制循环已损坏 - 即使您没有读那么多,您总是写出 4096 字节。应该是:

int bytesRead;
while((bytesRead = fileIn.read(outputByte)) != -1)
{
    out.write(outputByte, 0, byteRead);
}

...并且您应该使用 try-with-resources 或 finally block 来确保关闭流,即使出现异常也是如此。

(或者使用 Guava 等库中的实用方法。)

关于java - 文件下载时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22928812/

相关文章:

java - 使用 Geotools Dijkstra 最短路径查找器计算路径长度(以公里为单位的距离)

excel - 将多个范围的值添加到电子邮件正文

Excel 填充 IF 公式时不遵循顺序

PHP 下载会阻止其余请求

JAVA:如何下载servlet动态创建的网页

java - 获取当前时间和日期,采用 16 位十六进制(16 个字符)

java - 如何为 ehcache 构建单个 jar?

Eclipse 上的 Java Wildfly swarm

vba - 优化冗余 Excel VBA 代码

java - 安卓 : Download a single file in many parts