//临时工workbooks.zip文件
File zipFile = File.createTempFile("workbooks", ".zip");
ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFile));
for(..........){
//临时workbook.xlsx文件,workbook写入xlsx中
File tempFile = File.createTempFile(fileName, ".xlsx");
try (BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(tempFile))) {
workbook.write(bufferedOutputStream);
}
//写入zip文件中
File file = tempFile;
byte[] buffer = new byte[1024];
try (FileInputStream fileInputStream = new FileInputStream(file)) {
ZipEntry zipEntry = new ZipEntry(entryName);
zipOutputStream.putNextEntry(zipEntry);
int len;
while ((len = fileInputStream.read(buffer)) > 0) {
zipOutputStream.write(buffer, 0, len);
}
zipOutputStream.closeEntry();
}
}
zipOutputStream.close();
//写出到客户端下载
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=workbooks.zip");
InputStreamResource inputStreamResource = new InputStreamResource(new FileInputStream(zipFile));
return ResponseEntity
.ok()
.headers(headers)
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(inputStreamResource);
客户端接收响应下载文件
axios.post(
url, //自己填
data,//自己填
....
{responseType: 'blob'}).then((res) => {
this.visible_mergeMax_modal = false;
const blob = new Blob([res], { type: 'application/zip' });
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'yourfilename'+this.getCurrentDate()+'.zip');
document.body.appendChild(link);
link.click();
window.URL.revokeObjectURL(url);
document.body.removeChild(link);
}).catch((error) => {
console.error('Error generating and downloading ZIP:', error);
})