1

后端response返回一张图片,前端如何下载?

 1 year ago
source link: https://www.haorooms.com/post/response_image_download
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

后端response返回一张图片,前端如何下载?

2022年8月29日 52次浏览

之前文章关于文件下载介绍过很多,当然也有图片下载的,例如跨域图片下载JFIF格式解决方案及前端zip包下载,后端返回的是一张cdn的图片地址,我们如何下载?之前的文章介绍了下载方式及遇到的问题。

但是问题来了,后端返回cdn地址,我们前端下载是经过了转换的,不是原始的图片,假如后端图片大小是30kb,经过了压缩,但是我们经过了转换之后图片大小通常还是60kb,并非是原始的后端图片的大小。那么如何原封不动的下载后端返回的图片呢?直接reponse里面返回图片给到前端,前端如何下载呢?

前端下载后端返回的文件有很多方式,其实reponse中返回图片或者excel,分为get请求还是post请求,假如是get请求方式,那么很简单,excel的化,直接打开这个后端接口的地址就可以下载了,图片可以直接模拟点击,下载后端接口地址的图片就可以了,但是post方式不行,需要我们ajax请求之后下载,那么对于post形式的response里面是图片或者视频,我们不管后端是数据流还是二进制buffer,下载形式都是一种,下面我来介绍一下。

post 地址reponse里面返回图片下载方式

一:axiso等在请求request里面添加responseType:'blob'

记住,必须是request,在其他地方无效。例如:

const service = axios.create({
  baseURL: 'https://www.haorooms.com', // url = base url + request url
  withCredentials: true // send cookies when cross-domain requests
})

service.interceptors.request.use(
  config => {
    if(config.url.indexOf('haorooms/imagedownload')!=-1){
      config.responseType ='blob'
    }
    return config
  },
  error => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

二、转换为blob

let blob = new Blob([res])

三、创建地址,下载图片

let url = window.URL.createObjectURL(blob)
let downloadElement = document.createElement("a")
downloadElement.style.display = "none";
downloadElement.href = url
downloadElement.download = `${haorooms.imageName}${imageType == 'JPG' ? '.jpg' : '.png'}`
document.body.appendChild(downloadElement)
downloadElement.click()
document.body.removeChild(downloadElement)
window.URL.revokeObjectURL(url)

此方法对各种后端二进制数据均有效。

get请求下载excel

  window.location.href = `${origin}/downloadExcel?haoroomsquery=${encodeURIComponent(JSON.stringify(queryData))}`

关于canvas下载图片,下载jpg 出现JFIF这个格式的图片,可以看文章https://www.haorooms.com/post/jpg_jfif_change_zip 同时文章中也列出来zip包批量下载多个cdn文件地址的方法。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK