看碼是最好的表達:
public class DownloadFileDto implements Serializable {
private static final long serialVersionUID = 1L;
private String fileName = "";
private byte[] byteDataArr = new byte[0];
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public byte[] getByteDataArr() {
return byteDataArr;
}
public void setByteDataArr(byte[] byteDataArr) {
this.byteDataArr = byteDataArr;
}
@Override
public String toString() {
return "DownloadFileDto{" +
"fileName='" + fileName + '\'' +
", byteDataArr=" + Arrays.toString(byteDataArr) +
'}';
}
}
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@RestController
public class ZipDownloadController {
private static final Log logger = LogFactory.getLog(ZipDownloadController.class);
@RequestMapping(value = "/zipDownload", method = RequestMethod.GET)
public void downloadZipExcels(HttpServletResponse response) throws Exception {
List<DownloadFileDto> downloadFileDtoList = null;
/**獲取到文件字節(jié)數(shù)組*/
// downloadFileDtoList = fileService.getZipFileContent();
String fileName = "生成壓縮包下載.zip";
response.reset();
response.setCharacterEncoding("UTF-8");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "ISO8859-1"));
if (CollectionUtils.isNotEmpty(downloadFileDtoList)) {
try {
byte[] dataByteArr = zipFile(downloadFileDtoList);
response.getOutputStream().write(dataByteArr);
response.flushBuffer();
} catch (Exception e) {
logger.error("壓縮zip數(shù)據(jù)出現(xiàn)異常", e);
throw new RuntimeException("壓縮zip包出現(xiàn)異常");
}
}
}
public byte[] zipFile(List<DownloadFileDto> downloadFileDtoList) throws Exception {
/**將字節(jié)寫到一個字節(jié)輸出流里*/
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream out = new ZipOutputStream(baos);
try {
/**創(chuàng)建zip file in memory */
for (DownloadFileDto downloadFileDto : downloadFileDtoList) {
ZipEntry entry = new ZipEntry(downloadFileDto.getFileName());
entry.setSize(downloadFileDto.getByteDataArr().length);
out.putNextEntry(entry);
out.write(downloadFileDto.getByteDataArr());
out.closeEntry();
}
} catch (IOException e) {
logger.error("壓縮zip數(shù)據(jù)出現(xiàn)異常", e);
throw new RuntimeException("壓縮zip包出現(xiàn)異常");
} finally {
if (out != null) {
out.close();
}
}
return baos.toByteArray();
}
}
參考鏈接:
http://memorynotfound.com/create-zip-file-try-resources-java/
https://dzone.com/articles/how-compress-and-uncompress