如何将来自 URL(具有不同来源)的图像加载到文件 object 中?
How do I load an image from an URL (that has a different origin) into a File object?
起初我认为它应该像这样简单:
const img = document.createElement('img');
img.onload = () => { ... }
img.onerror = () => { ... }
img.src = url;
但后来发现我需要在 canvas 上绘制它,然后 toBlob()
。并且不要忘记 添加 CORS 和 crossorigin="anonymous"
到 img
标签。是不是有点太牵扯了?有没有更好的方法?
向您展示最终解决方案(您需要 CORS headers):
function getFileFromURL(url) {
return new Promise((resolve, reject) => {
const fileName = url.split('/').pop();
const img = document.createElement('img');
img.setAttribute('crossorigin', 'anonymous');
img.onload = () => {
const canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
canvas.toBlob(blob => {
resolve(new File([blob], fileName));
});
};
img.onerror = () => {
reject('something went wrong');
};
img.src = url;
})
}
CBroe 建议的解决方案可以说更好:
function getFileFromURL(url) {
const fileName = url.split('/').pop();
return fetch(url)
.then(response => {
return new File([response.data], fileName);
});
}
确保将 CORS headers 添加到请求中。
起初我认为它应该像这样简单:
const img = document.createElement('img');
img.onload = () => { ... }
img.onerror = () => { ... }
img.src = url;
但后来发现我需要在 canvas 上绘制它,然后 toBlob()
。并且不要忘记 添加 CORS 和 crossorigin="anonymous"
到 img
标签。是不是有点太牵扯了?有没有更好的方法?
向您展示最终解决方案(您需要 CORS headers):
function getFileFromURL(url) {
return new Promise((resolve, reject) => {
const fileName = url.split('/').pop();
const img = document.createElement('img');
img.setAttribute('crossorigin', 'anonymous');
img.onload = () => {
const canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
canvas.toBlob(blob => {
resolve(new File([blob], fileName));
});
};
img.onerror = () => {
reject('something went wrong');
};
img.src = url;
})
}
CBroe 建议的解决方案可以说更好:
function getFileFromURL(url) {
const fileName = url.split('/').pop();
return fetch(url)
.then(response => {
return new File([response.data], fileName);
});
}
确保将 CORS headers 添加到请求中。