我使用三个 servlet 来提供文件以供下载:
- ByteArrayDownloadServlet:用于小文件,例如报告或数据库中的文件
- FileDownloadServlet:用于小到大的文件
- MultipleFileDownloadServlet:使用请求的文件创建一个 zip 并将其流式传输
它们基于以下实现: 链接文本
我收到了几起关于下载损坏的投诉。问题是我无法模拟或在错误中找到模式:
- 有时有大文件
- 有时当用户请求下载多个文件和一个 zip 文件并动态创建时
- 有时文件较小,但许多用户同时请求
在帖子的上述评论中,有人报告了类似的问题,但没有解决方案。我也从这里读了很多线程,我越接近: 链接文本
有没有人遇到过类似的问题或有一些有效的示例代码?
谢谢,费利佩
@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");
}