Node实现压缩文件并下载
Node端代码
1、关键使用jszip包
2、路由配置:router.get(‘/download-zip’, controller.zip.downloadZip);
async downloadZip() {
const { ctx } = this
const zip = new jszip()
// 获取指定目录数据
const folderPath = path.resolve(__dirname, 'D:\\WorkSpace\\WarSim\\WarSim\\EventExport_CSV')
// 循环压缩目录下的数据,注意这里只压缩了第一层数据,如果多层级数据需要更复杂的写法
fs.readdirSync(folderPath).forEach(file => {
const filePath = path.join(folderPath, file)
const fileContent = fs.readFileSync(filePath)
zip.file(file, fileContent)
})
const zipContent = await zip.generateAsync({ type: 'nodebuffer' })
// 返回
ctx.set('Content-Type', 'application/octet-stream')
ctx.set('Content-Disposition', 'attachment; filename="files.zip"')
ctx.body = zipContent // 发送压缩包内容
}
Vue端代码
现在,当用户点击 Vue 前端的下载按钮时,后端将从指定目录中读取文件,创建一个 ZIP 文件,并将其发送给前端进行下载。
<template>
<div>
<button @click="downloadZip">Download Zip</button>
</div>
</template>
<script>
export default {
methods: {
downloadZip() {
// 从 Egg.js 服务器请求压缩文件
window.location.href = 'http://localhost:7001/download-zip';
}
}
}
</script>
注意:这个示例假设所有文件都位于一个非递归的目录中,如果你需要处理子目录等更复杂的场景,还需要进一步扩展这个基本的实现。