后端打包压缩包代码,前端接收响应下载

发布时间:2023年12月20日
//临时工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);
})
文章来源:https://blog.csdn.net/weixin_45031570/article/details/135101766
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。