繁体   English   中英

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

[英]Zip file created on server and download that zip, using java

我有以下代码从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
        }
    }
}

尝试这个:

@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();
}

参考

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM