14-下载图片
大约 1 分钟
下载文件的方式有好多种
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'
npm 下载
@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')
}
下载完是一个压缩包