vue+springboot批量下载
时间: 2023-11-19 07:07:25 浏览: 137
基于Vue和SpringBoot的资产出入库管理系统(源码+数据库)
5星 · 资源好评率100%
以下是Vue+SpringBoot批量下载的实现方法:
1.前端Vue代码:
```html
<template>
<div>
<el-button type="primary" @click="downloadAll">批量下载</el-button>
</div>
</template>
<script>
export default {
methods: {
downloadAll() {
// 获取需要下载的文件路径列表
const paths = ['path1', 'path2', 'path3'];
// 发送POST请求到后端下载接口
this.$axios.post('/downloadAll', paths, { responseType: 'blob' }).then(res => {
// 将二进制流转换为文件并下载
const blob = new Blob([res.data], { type: 'application/zip' });
const fileName = 'download.zip';
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob, fileName);
} else {
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = fileName; link.click();
window.URL.revokeObjectURL(link.href);
}
});
}
}
}
</script>
```
2.后端SpringBoot代码:
```java
@RestController
@RequestMapping("/download")
public class DownloadController {
@PostMapping("/downloadAll")
public void downloadAll(@RequestBody List<String> paths, HttpServletResponse response) throws IOException {
// 创建临时文件夹
File tempDir = new File(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
tempDir.mkdirs();
// 将需要下载的文件复制到临时文件夹中
for (String path : paths) {
File file = new File(path);
FileUtils.copyFileToDirectory(file, tempDir);
}
// 压缩临时文件夹中的文件
File zipFile = new File(System.getProperty("java.io.tmpdir"), "download.zip");
ZipUtil.pack(tempDir, zipFile);
// 设置响应头
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(zipFile.getName(), "UTF-8"));
// 将压缩后的文件写入响应流中
try (InputStream in = new FileInputStream(zipFile);
OutputStream out = response.getOutputStream()) {
IOUtils.copy(in, out);
out.flush();
}
// 删除临时文件夹和压缩文件
FileUtils.deleteDirectory(tempDir);
FileUtils.deleteQuietly(zipFile);
}
}
```
阅读全文