Java servlet : problem with corrupt file download

标签 java servlets download corruption

我使用三个 servlet 来提供文件下载:

  • ByteArrayDownloadServlet:用于小文件,例如报告或数据库中的文件
  • FileDownloadServlet:用于从小到大的文件
  • MultipleFileDownloadServlet:使用请求的文件创建一个 zip 并将其传输

它们基于以下实现: link text

我收到了几起有关下载损坏的投诉。问题是我无法模拟或找到错误中的模式:

  • 有时文件很大
  • 有时,当用户请求下载多个文件和动态创建的 zip 文件时
  • 有时文件较小,但许多用户同时请求

在上述帖子的评论中,有人报告了类似的问题,但没有解决方案。我还从这里阅读了很多主题,这让我更加接近: link text

有人遇到过类似的问题或有一些有效的示例代码吗?

谢谢, 费利佩

@Override
@SuppressWarnings("unchecked")    
protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
{
    HttpSession session = request.getSession();
    List<File> selectedFileList = (List<File>) session.getAttribute("selectedFileList");

    if(selectedFileList == null)
    {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED, "Lista de arquivos não informada");
        return;
    }

    response.reset();
    response.setContentType("application/zip");        

    response.setHeader("Content-Disposition", "attachment; filename=\""
        + "atualizacoes_"
        + new Date().getTime() + ".zip" + "\"");

    ZipOutputStream output = null;

    try
    {
        output = new ZipOutputStream(response.getOutputStream());

        for(File file : selectedFileList)
        {
            InputStream input = new FileInputStream(file);
            output.putNextEntry(new ZipEntry(file.getName()));                

            byte[] buffer = new byte[DownloadHandler.DEFAULT_BUFFER_SIZE];
            int length;
            while((length = input.read(buffer)) > 0)
            {
                output.write(buffer, 0, length);
            }

            output.closeEntry();
            input.close();
        }            

     output.finish();
     output.flush();
     output.close();
  }
  catch(Exception e) 
  {
      if(!(e instanceof ClientAbortException))
      {
          new ExceptionMail(getClass().getSimpleName(), e);
      }
    }
  finally
  {            
        session.removeAttribute("selectedFileList");        
  }

最佳答案

从 servlet 下载随机损坏的最常见原因是 servlet 不是线程安全的和/或它将字节作为字符读取。在同一 session 或 servletcontext 中的请求之间共享基于请求或 session 的数据也是导致此问题的一个可能原因。

关于Java servlet : problem with corrupt file download,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3855465/

相关文章:

java - 用于 java 生成文件夹的 Paho 客户端,如 paho101658642587966-tcp1270011883。这有什么重要性?

java - 代理 servlet 和 iframe 从另一个域运行站点

java - 如何将 Sling serlvet 中的 sling.servlet.resourceTypes 设置为相对于自身的路径(到 serlvet 的资源)?

c++ - URLDownloadToFile 总是返回 S_OK

java - 邮件程序插件抛出 NullPointerException

java - 如何在 Spring Controller 中获取调度程序 servlet 名称

jsf - 以编程方式添加上下文参数?

android - 无法在 Android 上下载文件,而在 PC 上下载正常(亚马逊)

java - 如何正确下载多个图像(视频缩略图)

java - 自动过期并删除SQLite数据库中的记录