TypeError: Failed to execute ‘createObjectURL‘ on ‘URL‘: Overload resolution failed

TypeError: Failed to execute ‘createObjectURL‘ on ‘URL‘: Overload resolution failed

//request.js
service.interceptors.response.use(
  (response) => {
    const res = response.data
    
    // 下载文件
    if (!res.code) {
      return response
    }
    ...
  },
  (error) => {
  	...
  }
export function downloadQrcode(params) {
  return request({
    url: '/multiplayer-draw/download-qrcode',
    method: 'get',
    // headers: { 'Content-Type': 'image/png; charset=UTF-8' }, 
    responseType: 'blob',		// response类型
    params
  })
}
downloadQrcode({id: this.id}).then(res => {
  console.log(res,'res'); 
  var a = document.createElement('a')
  document.body.appendChild(a)
  a.style = 'display: none'
  let url = window.URL.createObjectURL(res); 
  a.href =  url
  a.download = '二维码.png'
  a.click()
  a.remove()
  window.URL.revokeObjectURL(url) // 释放url
})

发现报错:

同时,发现接口是有返回值的:

再看打印的res:
发现打印的res并不是最后我们需要的Blob值,我们需要的是Blob类型的值,发现正是res.data(但是从浏览器控制台并不能看出data),所以应该修改request.js为:

const res = response.data

 // 下载文件
 if (!res.code) {
   return response.data //等同于 return res
 }

此时发现打印的res为:

也没有“TypeError: Failed to execute ‘createObjectURL’ on ‘URL’: Overload resolution failed”这个报错了,成功下载了图片。

还有第二种方法:创建一个Blob

downloadQrcode({id: this.id}).then(res => {
   console.log(res,'res');
   var a = document.createElement('a')
   document.body.appendChild(a)
   a.style = 'display: none'
   //增加了下面三行
   let blob = new Blob([res], {
     type: "image/png",
   }); 
   let url = window.URL.createObjectURL(blob); 
   a.href =  url
   a.download = '二维码'
   a.click()
   a.remove()
   window.URL.revokeObjectURL(url) // 释放url
 })

发现打印的res没变

但是也没有出现“TypeError: Failed to execute ‘createObjectURL’ on ‘URL’: Overload resolution failed”报错,而且a.download = '二维码.png’变成了a.download = ‘二维码’,也成功下载了图片。

转载请说明出处内容投诉
CSS教程_站长资源网 » TypeError: Failed to execute ‘createObjectURL‘ on ‘URL‘: Overload resolution failed

发表评论

欢迎 访客 发表评论

一个令你着迷的主题!

查看演示 官网购买