【问题标题】:Error while file download下载文件时出错
【发布时间】:2014-04-08 06:06:13
【问题描述】:

在我的 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打开。

我该怎么做??

【问题讨论】:

  • 你不使用 Java 7 吗?

标签: java excel download


【解决方案1】:

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

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 块来确保即使出现异常也关闭您的流。

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

【讨论】:

  • ... 或者直接使用Files.copy() ;)
  • @Zedai:你把xslx 错写成xlsx了吗?
猜你喜欢
  • 2014-07-01
  • 2013-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-27
  • 2021-04-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多