在服务器上创建Zip文件并使用java下载该zip文件

编程入门 行业动态 更新时间:2024-10-25 02:24:52
本文介绍了在服务器上创建Zip文件并使用java下载该zip文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有以下代码从mkyong到本地的zip文件。但是,我的要求是在服务器上压缩文件并需要下载。可以帮助任何人。

I have the below code got from mkyong, to zip files on local. But, my requirement is to zip files on server and need to download that. Could any one help.

代码写入zipFiles:

code wrote to zipFiles:

public void zipFiles(File contentFile, File navFile) { byte[] buffer = new byte[1024]; try{ // i dont have idea on what to give here in fileoutputstream FileOutputStream fos = new FileOutputStream("C:\\MyFile.zip"); ZipOutputStream zos = new ZipOutputStream(fos); ZipEntry ze= new ZipEntry(contentFile.toString()); zos.putNextEntry(ze); FileInputStream in = new FileInputStream(contentFile.toString()); int len; while ((len = in.read(buffer)) > 0) { zos.write(buffer, 0, len); } in.close(); zos.closeEntry(); //remember close it zos.close(); System.out.println("Done"); }catch(IOException ex){ ex.printStackTrace(); } }

我可以在fileoutputstream中提供什么? contentfile和navigationfile是我从代码创建的文件。

what could i provide in fileoutputstream here? contentfile and navigationfile are files i created from code.

推荐答案

如果您的服务器是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 } } }

更多推荐

在服务器上创建Zip文件并使用java下载该zip文件

本文发布于:2023-05-28 06:52:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/315068.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   器上   zip   Zip   java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!