有些项目,如果服务器图片资源不能互相访问时,需要下载后并上传到另一个服务器,网上很多都是转 base64 字符串后上传到服务器,下面我们试一下下载为 blob 大文件并转为 file 对象进行上传。
// url 文件地址转为文件对象
function urlToFile(url, fileName) {
return new Promise((resolve, reject) => {
fetch(url).then(res => res.blob()).then(blob => {
let file = new window.File([blob], fileName);
resolve(file);
}).catch(error => {
console.log("error", error);
reject(error)
});
});
}
// 获取文件对象数组
function getFileList(urls) {
return new Promise(async (resolve) => {
let fileList = [];
for (let i = 0; i < urls.length; i++) {
let fileName = urls[i].substring(urls[i].lastIndexOf('/') + 1);
let file = await this.urlToFile(urls[i], fileName);
if(file instanceof window.File){
fileList.push(file);
}
}
resolve(fileList);
});
}
// 上传文件对象
function uploadFile(urls){
return new Promise(async (resolve) => {
let fileList = await this.getFileList(urls);
let formData = new FormData();
for (let i = 0; i < fileList.length; i++) {
formData.append("files", fileList[i]);
}
fetch("http://localhost:8080/upload/img/list", {
method: "POST",
body: formData
}).then(result => result.json()).then(json => {
console.log("result", json);
resolve(json);
})
});
}