我使用三个 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/