【问题标题】:Zip file created on server and download that zip, using java在服务器上创建的 Zip 文件并使用 java 下载该 zip
【发布时间】:2014-07-01 23:35:12
【问题描述】:

我有以下从 mkyong 获得的代码,用于压缩本地文件。但是,我的要求是在服务器上压缩文件并需要下载它。谁能帮忙。

将代码写入 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();
    }
}

我可以在文件输出流中提供什么? contentfile 和 navigationfile 是我用代码创建的文件。

【问题讨论】:

  • 请澄清您的问题。此代码打算在服务器或客户端上运行吗?如果是服务器,什么样的服务器?以 Servlet 为例?
  • 实现一个服务器发送数据,一个客户端接收数据?或者使用当前流行的协议,如 ssh 和 ftp 等。

标签: java zip java-io


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    试试这个:

    @RequestMapping(value="download", method=RequestMethod.GET)
    public void getDownload(HttpServletResponse response) {
    
        // Get your file stream from wherever.
        InputStream myStream = someClass.returnFile();
    
        // Set the content type and attachment header.
        response.addHeader("Content-disposition", "attachment;filename=myfilename.txt");
        response.setContentType("txt/plain");
    
        // Copy the stream to the response's output stream.
        IOUtils.copy(myStream, response.getOutputStream());
        response.flushBuffer();
    }
    

    Reference

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-16
      • 2015-08-28
      • 1970-01-01
      • 2022-10-16
      相关资源
      最近更新 更多