ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2019-07-22 21:03:07  阅读:170  来源: 互联网

标签:java zip java-io


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

代码写入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是我从代码创建的文件.

解决方法:

如果您的服务器是一个servlet容器,只需编写一个HttpServlet来进行压缩并为该文件提供服务.

您可以将servlet响应的输出流传递给ZipOutputStream的构造函数,zip文件将作为servlet响应发送:

ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());

在压缩之前不要忘记设置响应mime类型,例如:

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
        }
    }
}

标签:java,zip,java-io
来源: https://codeday.me/bug/20190722/1506840.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有