controller 代码
@ApiOperation(value = "系统文件批量下载接口", produces = "application/octet-stream")
@PostMapping(value = "/downloadzip")
public void downloadzip(@ApiParam("文件 url 路径") @RequestBody CommonProjectSearchVo searchVo, HttpServletResponse response) throws Exception {
String[] paths = searchVo.getPaths();
if (Objects.isNull(searchVo) || Objects.isNull(searchVo.getPaths()) || paths.length == 0) {
throw new CustomException("请选择附件");
}
if (paths.length != 0) {
String myFileName = OperatorUtils.getOperator().getOperator()
+ String.valueOf(new Date().getTime()) + ".zip";
String zipFilePath = downloadPath + "/" + myFileName;
File file = new File(downloadPath);
if (!file.exists() && !file.isDirectory()) {
file.mkdir();
}
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFilePath));
for (String path : paths) {
FileConvertUtil.fileToZip(path, zipOut);
}
zipOut.close();
String fileName = new String((myFileName).getBytes(), "ISO-8859-1");
response.setHeader("Content-Disposition", "attchment;filename=" + fileName);
ServletOutputStream outputStream = response.getOutputStream();
FileInputStream inputStream = new FileInputStream(zipFilePath);
IOUtils.copy(inputStream, outputStream);
inputStream.close();
File fileTempZip = new File(zipFilePath);
fileTempZip.delete();
}
}
工具类FileConvertUtil.fileToZip
public class FileConvertUtil {
public static void fileToZip(String filePath, ZipOutputStream zipOut) throws IOException {
filePath = getEncodeUrl(filePath).replaceAll("\\+", "%20");
File file = new File(filePath);
String fileName = FilenameUtils.getBaseName(URLDecoder.decode(file.getName(), "UTF-8")) + "-"
+ String.valueOf(new Date().getTime()) + "."
+ FilenameUtils.getExtension(file.getName());
InputStream fileInput = getInputStream(filePath);
byte[] bufferArea = new byte[1024 * 10];
BufferedInputStream bufferStream = new BufferedInputStream(fileInput, 1024 * 10);
zipOut.putNextEntry(new ZipEntry(fileName));
int length = 0;
while ((length = bufferStream.read(bufferArea, 0, 1024 * 10)) != -1) {
zipOut.write(bufferArea, 0, length);
}
fileInput.close();
bufferStream.close();
}
public static InputStream getInputStream(String filePath) throws IOException {
InputStream inputStream = null;
URL url = new URL(filePath);
URLConnection urlconn = url.openConnection();
urlconn.connect();
HttpURLConnection httpconn = (HttpURLConnection) urlconn;
int httpResult = httpconn.getResponseCode();
if (httpResult == HttpURLConnection.HTTP_OK) {
inputStream = urlconn.getInputStream();
}
return inputStream;
}
}