前端
show(e) { this.axios({ url: this.url.labelPrint, method: 'post', responseType: 'blob', type: 'multipart/form-data', timeout: 150000, data: { //封装要用的参数 sampleNumber: e.reportNumber, sampleName: e.sampleName, sampingDate: e.sampingDate, deliveryDate: e.deliveryDate, deliveryDates: e.deliveryDates, deliveryAddress: e.deliveryAddress, standbyWhere: e.standbyWhere, sampleQuantity: e.sampleQuantity, key: e.id } }).then(res => { const elink = document.createElement('a') elink.style.display = 'none' document.body.appendChild(elink); //重名名的名字 const fileName = e.reportNumber + e.sampleName+'.zip' elink.download = fileName let binaryData = []; binaryData.push(res); elink.href = window.URL.createObjectURL(new Blob(binaryData)); elink.click(); URL.revokeObjectURL(elink.href); // 释放URL 对象 this.$message.success("下载成功"); document.body.removeChild(elink); }) },
java后台
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try (ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream)) {
//生成多个文件
for (int a = shu; a > 0; a--) {
// 创建每个标签docx文件
String fileName = sampleNumber + '-' + a + sampleName + "标签.docx";
String filePath = csbcbhUrl.getUrlFile() + fileName;
contractTestReportController.parse(templatePath, templateName, filePath, map);
// 将标签文件添加到 Zip 文件中
byte[] buffer = new byte[1024];
FileInputStream inputStream = new FileInputStream(filePath);
zipOutputStream.putNextEntry(new ZipEntry(fileName));
int len;
while ((len = inputStream.read(buffer)) != -1) {
zipOutputStream.write(buffer, 0, len);
}
inputStream.close();
zipOutputStream.closeEntry();
// 记录 Zip 文件的文件名
objects.add(filePath);
}
// 设置 Zip 文件的响应类型和头信息
httpServletResponse.setContentType("application/zip");
httpServletResponse.setHeader("Content-Disposition", "attachment; filename=\"sample_labels.zip\"");
}
// 将所有 Zip 文件的字节下载到客户端
ServletOutputStream out = httpServletResponse.getOutputStream();
outputStream.writeTo(out);
out.flush();
out.close();
outputStream.close();
// 删除临时生成的文件
for (String filePath : objects) {
File file = new File(filePath);
file.delete();
}