下载文件的方式有好多种
1.download 直接下载
这个文件信息应该存数据库 我们这儿演示就写死 了
import { Controller, Post, UseInterceptors, UploadedFile, Get, Res } from '@nestjs/common'; import { UploadService } from './upload.service'; import { FileInterceptor, FilesInterceptor } from '@nestjs/platform-express' import type { Response } from 'express' import {join} from 'path' @Controller('upload') export class UploadController { constructor(private readonly uploadService: UploadService) { } @Post('album') @UseInterceptors(FileInterceptor('file')) upload(@UploadedFile() file) { console.log(file, 'file') return '峰峰35岁憋不住了' } @Get('export') downLoad(@Res() res: Response) { const url = join(__dirname,'../images/1662894316133.png') // res // console.log(url) res.download(url) // return true } }
2.使用文件流的方式下载
可以使用compressing把他压缩成一个zip包
import {zip} from 'compressing'
@Get('stream') async down (@Res() res:Response) { const url = join(__dirname,'../images/1662894316133.png') const tarStream = new zip.Stream() await tarStream.addEntry(url) res.setHeader('Content-Type', 'application/octet-stream'); res.setHeader( 'Content-Disposition', `attachment; filename=xiaoman`, ); tarStream.pipe(res) }
前端接受流
const useFetch = async (url: string) => { const res = await fetch(url).then(res => res.arrayBuffer()) console.log(res) const a = document.createElement('a') a.href = URL.createObjectURL(new Blob([res],{ // type:"image/png" })) a.download = 'xiaman.zip' a.click() } const download = () => { useFetch('http://localhost:3000/upload/stream') }