NestJS之09- 图片下载

604 阅读1分钟

1. 第一种方式 url形式

后端:

upload.controller.ts 中加入

  @Get('download')
  download(@Res() res: Response) {
    console.log('打印***res', res);
    const url = join(__dirname, '../images/1681344671860.png');
    res.download(url);
  }

前端:

使用fetch进行请求的

window.open('http://localhost:3000/upload/download') // 默认新标签页,会闪一下
location.href = 'http://localhost:3000/upload/download' // 不会闪

image.png

2. 第二种方式 以流的形式进行传输

2.1 zip 压缩

npm i compressing -S

后端:

import { zip } from 'compressing';
 @Get('stream')
  async down(@Res() res: Response) {
    const url = join(__dirname, '../images/1681344671860.png');
    const tarStream = new zip.Stream();
    await tarStream.addEntry(url);
    res.setHeader('Content-Type', 'application/octet-stream');
    tarStream.pipe(res);
  }

前端:

const res = await fetch('http://localhost:3000/upload/stream').then(res => res.arrayBuffer())
const a = document.createElement('a')
a.href = URL.createObjectURL(new Blob([res],{
}))
a.download = 'a.zip' // HTML5新增的属性,指定保存文件名,可以不要后缀
a.click()

2.2 流形式

 @Get('stream')
  async down(@Res() res: Response) {
    const url = join(__dirname, '../images/1681344671860.png');
    const readStream = fs.createReadStream(url);
    res.setHeader('Content-Type', 'application/octet-stream');
    readStream.pipe(res);
  }

前端:

const res = await fetch('http://localhost:3000/upload/stream').then(res => res.arrayBuffer())
const a = document.createElement('a')
a.href = URL.createObjectURL(new Blob([res],{
// type:"image/png"  如何设置成png 则是预览
}))
a.download = 'a.png'
a.click()

常规导出

export function $_downloadFile(obj, name, suffix) {
  const DOWNLOAD_TYPE_MAP = {
    xls: 'application/vnd.ms-excel',
    xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    doc: 'application/msword',
    docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    pdf: 'application/pdf'
  }
  if (!DOWNLOAD_TYPE_MAP[suffix]) {
    throw new Error('请传入文件下载的格式后缀,eg:xls,xlsx,doc,docx,pdf')
  }
  const blob = new Blob([obj], {
    type: DOWNLOAD_TYPE_MAP[suffix]
  })
  const fileName = `${name}.${suffix}`
  let link = document.createElement('a')
  document.body.appendChild(link)
  link.href = URL.createObjectURL(blob)
  link.setAttribute('download', fileName)
  link.click()
  document.body.removeChild(link)
  URL.revokeObjectURL(link.href) // 销毁url对象
}