res.attachment()方法的用途是什么

时间:2019-03-13 21:05:47

标签: node.js express archiverjs

我想添加一些功能,使用户可以转到路线并下载 zip 。要制作 zip ,我使用的是 archiver ,如果我浏览了 archiver 的文档,那么第一步应该是创建一个写流,然后将其传递给zip(output)方法(输出是写流),然后下载该文件,我可以使用res.download(filepath),但是我遇到了一种解决方案,其中使用res.attachment(download.zip),然后将 res 传递到zip(res),并在访问路径时下载压缩文件。

我在这里不了解res.attachment()的性质。它可以作为写入流使用吗?如果是的话, res 包含的数据也会被写入文件吗?
P.S:我已经阅读了快速文档,但是关于attachment()方法的信息不多

代码

download() {
    const files = this.result.files
    const zip = archiver('zip', {
        zlib: {level: 9}
    })
    const response = this.response

    response.attachment('download.zip')
    zip.pipe(response)

    files.forEach((file) => {
        const filePath = path.join(uploadDir, file.filename)
        zip.file(filePath, {name: file.originalname})
    })

    zip.finalize()
}

0 个答案:

没有答案