-
業務場景
- 需求: 復制一個模塊, 該模塊內容含有圖片文件.
- 可提供的數據有: 該模塊的相關信息(id等), 以及圖片路徑.
- 后台提供接口中, 需要傳file字段.
-
知識儲備
- xhr配置
- blob對象
- new File()方法
-
函數實現
//util.js
export function getImageFileFromUrl(url, imageName) {
// imageName一定要帶上后綴
let p = new Promise((resolve, reject) => {
var blob = null;
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.setRequestHeader('Accept', 'image/jpeg');
xhr.responseType = "blob";
xhr.onload = () => {
blob = xhr.response;
let imgFile = new File([blob], imageName, {type: 'image/jpeg'});
resolve(imgFile);
};
xhr.send();
});
return p;
}