node批量下载文件,打包成压缩包(以图片做例子)

备注说明:

1.需要依赖 archiver
2.调用方法的时候,一定要加上try...catch...
try {
await all_down(list,response)
}catch (e) {
}
3.所有的文件流追加完后,一定记得
archive.finalize();

 1 //引入依赖
 2 var archiver = require('archiver');
 3 //定义参数
 4  let list=[{path:‘img1.png’,name:'图片1'},{path:‘img2.png’,name:'图片2'}]
 5 
 6 async function all_down(list,response) {
 7     var archive = archiver('zip');//设置压缩包类型
 8     archive.on('error', function(err) {
 9         throw err;
10     });
11     archive.store = true;  
12     archive.pipe(response);
13 
14     for (let i=0;i<list.length;i++) {
15         let item=list[i]
16         let path=item.path
17         let stream =fs.createReadStream(path);//获取图片流
18         let index=path.lastIndexOf('.')
19         let extname=path.substring(index)//获取图片后缀名
20         let name = item.name+extname;  //定义成需要的名称
21         archive.append(stream, { name: name })
22            if (i==list.length-1){
23              //最后一个文件流append到archive后,关闭archive
24                archive.finalize();
25            }
26     };
27     var fileName = 'text.zip';//压缩包名称
28    //设置header
29     response.setHeader('Content-Type', 'application/x-zip');
30     response.setHeader("Content-Disposition", "attachment; filename=" + new Buffer(fileName).toString('binary'));
31     archive.on('finish', function(err) {
32         response.end('binary');
33     });
34 }
View Code

 最终结果:

 

 

posted @ 2020-04-16 16:00  打工的工人  阅读(1399)  评论(0编辑  收藏  举报