首页 > 解决方案 > Without creating ZIP file on server (hard disk) how to let client download a ZIP file with custom selected files?

问题描述

I have a requirement in which I will let users choose a list of files (using check box) and let him download all the files he selected to download by zipping them and show him the download prompt.

I am able to do this by creating the zip file on the server hard disk and making use of this file and let the user to download the files, everything is going fine. But I don't want to create a zip file on the hard-disk, I want to create it on the fly and let user download the zip file, at any point of time there should be no .zip file on my server.

标签: javaspringspring-boot

解决方案


在硬盘上创建文件或通过 spring-mvc-endpoint 返回文件没有区别。只要确保你重定向ZipOutputStream到你的response.getOutputStream()

例如:

response.setHeader("Content-disposition","attachment; filename=myfile.zip");         
ZipOutputStream stream = new ZipOutputStream(response.getOutputStream());
ZipEntry zipEntry = new ZipEntry(myFile);
zipStream.putNextEntry(zipEntry);
//write your file-content to zipstream e.g. like this
zipStream.write(Files.readAllBytes(Paths.get("myfile")));

推荐阅读