11

跨域图片下载JFIF格式解决方案及前端zip包下载

 3 years ago
source link: https://www.haorooms.com/post/jpg_jfif_change_zip
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.

之前文章有写过图片下载,同域名图片,只要添加download就可以下载下来,但是download在跨域图片中不起作用,因此,可以用canvas方式或者xhr方式下载。但是呢,通过canvas或者xhr下载下来的图片,在win10上面,可能会变成怪异的JFIF,这个如何解决呢?

推荐使用file-saver 这个库

npm install file-saver --save

import { saveAs } from 'file-saver'

 saveAs("https://www.haorooms.com/upload/image.jpg", "haorooms.jpg");

这样就可以了,超级简单。

通过zip包下载多个img图片

首先,我们需要jszip 这个库

下载多个在线img图片地址并打包成zip的方法如下:

  let zip = new JSZip()
  var myFile = zip.folder()
  let promiseAllData =[]
  res.data.forEach(imglist=>{// res.data是图片对象数组[{id,width,height,preview_url:'https://www.haorooms.com/1.jpg'}]这样的格式
    (function(n) {
        promiseAllData.push(loadAsArrayBuffer(n.preview_url).then(buffer=>{
          myFile.file(`${n.id}-${n.width}*${n.height}.${checkAllimageType=='JPG'?'jpg':'png'}`,buffer)//checkAllimageType是JPG/PNG
        })) 

  })(imglist)
  })
  Promise.all(promiseAllData).then(result=>{
     zip.generateAsync({type:'blob'}).then((content)=> {
       saveAs(content, `批量制图-${new Date().getTime()}.zip`)
     })
  })

//loadAsArrayBuffer 这个方法是图片下载的promise封装方法

export function loadAsArrayBuffer(url) {
  return new Promise((resolve,reject)=>{
    var xhr = new XMLHttpRequest();
    xhr.open("GET", url);
    xhr.responseType = "arraybuffer";
    xhr.onerror = function() {/* handle errors*/};
    xhr.onload = function() {
      if (xhr.status === 200) {
        resolve(xhr.response)}
      else {
        reject({})
      }
    }
    xhr.send();
  })
}

上面就是跨域图片下载JFIF格式解决方案及前端zip包下载,相关代码。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK