foreword
In the previous article, I wrote about downloading images. Images with the same domain name can be downloaded as long as you add download, but download does not work for cross-domain images. Therefore, you can use canvas or xhr to download. However, pictures downloaded through canvas or xhr may become weird JFIF on win10, how to solve this?
solution
It is recommended to use the file-saver library
npm install file-saver --save
import { saveAs } from 'file-saver'
saveAs("https://www.haorooms.com/upload/image.jpg", "haorooms.jpg");
That's it, super easy.
Download multiple img images via zip package
First, we need the jszip library
The method of downloading multiple online img image addresses and packaging them into zip is as follows:
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 This method is a promise encapsulation method for image download
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();
})
}