下载文件
download(@Res() res:Response){
const url = 'url.png'
res.download(url)
}
npm install compressing
import { zip } from 'compressing';
@get()
async download(@Res() res:Response){
const url = join(__dirname, 'image/1747291958149.jpg')
const tarStream = new zip.Stream()
await tarStream.addEntry(url)
res.setHeader('Content-Type','application/octet-stream')
res.setHeader('Content-Disposition','attachment;filename=alrcly')
tarStream.pipe(res)
}
不要直接操作响应对象
在 NestJS 中,如可以,不要直接操作响应对象(@Res)。有需要可以使用 @Headers()
、@HttpCode()
这样的装饰器。文件下载,使用面向响应式的方式处理文件 StreamableFile()
import { StreamableFile } from '@nestjs/common';
import { zip } from 'compressing';
@get()
@Header('Content-Type','application/octet-stream')
@Header('Content-Disposition','attachment;filename=alrcly')
async download(){
const url = join(__dirname, 'image/1747291958149.jpg')
const tarStream = new zip.Stream()
await tarStream.addEntry(url)
return new StreamableFile(tarStream)
}
import { StreamableFile } from '@nestjs/common';
import { createReadStream } from 'fs';
async down() {
const url = join(__dirname, 'image/1747291958149.jpg')
const file = createReadStream(url)
return new StreamableFile(file)
}
扩展知识,前端如何接收流文件
const useFetch = async (url) => {
const res = await fetch(url).then((res) => res.arrayBuffer())
const blob = new blob([res])
const phoneURL = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = phoneURL
a.download = 'name.zip'
a.click()
}