不废话上代码
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@Controller
@RequestMapping("/downloadZip")
@Slf4j
public class DownloadZipController {
@Resource
private XxxService xxxService ;
@RequestMapping("/downloadZipFile")
public String downLoadFile(HttpServletResponse response, String fileUrl, String id, ModelMap modelMap) throws Exception {
String fileName = "";
List<String> list = new ArrayList<>();
List<File> fileList = new ArrayList<>();
List<Model> listPa = xxxService .getModel(id);
if (listPa.size() > 0) {
for (int i = 0; i < listPa.size(); i++) {
list.add(fileUrl + listPa.get(i).getAttach());
fileList.add(new File(fileUrl + listPa.get(i).getAttach()));
}
if (StringUtils.isEmpty(listPa.get(0).getName())) {
fileName = "文件";
} else {
fileName = listPa.get(0).getName();
}
//响应头的设置
response.reset();
response.setContentType("application/force-download");
response.addHeader("Content-Disposition", "attachment;fileName=" + new String(fileName.getBytes("UTF-8"), "iso-8859-1") + ".zip");
response.setContentType("application/octet-stream;charset=utf-8");
//设置压缩流:直接写入response,实现边压缩边下载
Charset charset = Charset.forName("UTF-8");
ZipOutputStream zipos = null;
OutputStream out = response.getOutputStream();
zipos = new ZipOutputStream(new BufferedOutputStream(out), charset);
//设置压缩方法
zipos.setMethod(ZipOutputStream.DEFLATED);
DataOutputStream os = null;
try {
//循环将文件写入压缩流
for (int i = 0; i < list.size(); i++) {
URL url = new URL(list.get(i));
URLConnection conn = url.openConnection();
InputStream inputStream = conn.getInputStream();
//添加ZipEntry,并ZipEntry中写入文件流
zipos.putNextEntry(new ZipEntry(fileList.get(i).getName()));
os = new DataOutputStream(zipos);
byte[] buff = new byte[1024 * 10];
int len = 0;
//循环读写
while ((len = inputStream.read(buff)) > -1) {
os.write(buff, 0, len);
}
//关闭此文件流
inputStream.close();
//关闭当前ZIP项,并将流放置到写入的位置。下一个条目。
zipos.closeEntry();
}
//释放资源
out.flush();
os.flush();
os.close();
zipos.close();
out.close();
//return null;
} catch (IOException e) {
e.printStackTrace();
} finally {
//释放资源
os.close();
zipos.close();
out.close();
}
return null;
}else{
modelMap.put("code","没有可下载的内容,如需下载请在工程资料中下载");
return "views/download";
}
}
}