使用express-zip将多个文件下载为zip文件的解决方法如下所示:
首先,确保已安装express和express-zip模块:
npm install express express-zip
然后,创建一个Express应用程序,并在其中包含以下代码:
const express = require('express');
const app = express();
const zip = require('express-zip');
app.get('/download', (req, res) => {
const files = [
{ path: '/path/to/file1.txt', name: 'file1.txt' },
{ path: '/path/to/file2.txt', name: 'file2.txt' }
];
res.zip(files, 'archive.zip');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
在上述示例中,我们创建了一个/download
的GET路由,其中files
数组包含要下载为zip文件的文件路径和名称。最后一行res.zip(files, 'archive.zip')
使用express-zip模块将文件打包成zip文件并发送到客户端。
确保将/path/to/file1.txt
和/path/to/file2.txt
替换为实际文件的路径。还可以根据需要添加更多的文件到files
数组中。
最后,通过运行以下命令启动服务器:
node app.js
然后,可以通过访问http://localhost:3000/download
来下载zip文件。
以上就是使用express-zip将多个文件下载为zip文件的解决方法,希望对你有帮助!