更新时间:2023-01-22 11:19:17
如果您的服务器是servlet容器,只需写一个 HttpServlet
执行压缩并提供文件。
If your server is a servlet container, just write an HttpServlet
which does the zipping and serving the file.
您可以将servlet响应的输出流传递给 ZipOutputStream 并且zip文件将作为servlet响应发送:
You can pass the output stream of the servlet response to the constructor of ZipOutputStream
and the zip file will be sent as the servlet response:
ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
不要忘记在压缩之前设置响应mime类型,例如:
Don't forget to set the response mime type before zipping, e.g.:
response.setContentType("application/zip");
全貌:
public class DownloadServlet extends HttpServlet {
@Override
public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment; filename=data.zip");
// You might also wanna disable caching the response
// here by setting other headers...
try ( ZipOutputStream zos = new ZipOutputStream(response.getOutputStream()) ) {
// Add zip entries you want to include in the zip file
}
}
}