【发布时间】:2021-03-23 12:21:42
【问题描述】:
我试图弄清楚如何从其他域的图像 URL 中获取图像,然后发布到我的服务器。但我遇到了核心问题。
我正在制作一个愿望清单页面,用户可以在其中输入来自任何网站的产品的网址。我的服务器抓取产品信息和产品图像的 URL 并将其发送给客户端。用户细化信息并选择所需的图像。此信息被发送到后端以创建包含产品信息和商品图片的愿望清单商品。
抓取产品图片和产品信息
图像和信息在愿望清单上
污染的画布
我尝试使用画布抓取和裁剪图像并将其发送到我的后端。但是,当您将未经 CORS 批准从其他来源加载的图像绘制到画布中时,画布就会被污染。
在受污染的画布上调用以下任何一个都将导致错误:
- 在画布上下文中调用
getImageData()- 在元素本身上调用
toBlob()- 在画布上调用
toDataURL()
export async function toDataURLCanvas(src, outputFormat) {
return new Promise((resolve) => {
const img = new Image();
img.onload = async function () {
console.log(this);
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = 200;
canvas.height = 200;
ctx.drawImage(this, 0, 0); //this is where you would crop the image
const blob = await new Promise((resolve) => {
// results in "Failed to execute 'toBlob' on 'HTMLCanvasElement': Tainted canvases may not be exported.""
canvas.toBlob((blob) => {
resolve(blob);
}, 'image/jpg');
});
resolve(blob);
};
img.src = src;
});
}
这给出了一个错误:
Failed to execute 'toBlob' on 'HTMLCanvasElement': Tainted canvases may not be exported.
所以我不能使用画布将图像 URL 转换为格式以发送到我的后端,例如 blob。
XHR
我尝试使用XMLHttpRequest() 将 URL 转换为数据 URL
async function toDataURLXHR(url) {
return new Promise((resolve) => {
var xhr = new XMLHttpRequest();
xhr.onload = function () {
var reader = new FileReader();
reader.onloadend = function () {
resolve(reader.result);
};
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
});
}
但是 CORS 可能是个问题。我在浏览器控制台中得到了这个:
Access to XMLHttpRequest at 'https://cdn-images.farfetch-contents.com/15/40/82/30/15408230_28680969_600.jpg' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
不可能?
似乎无法从一个站点抓取图像并将其发送到我的服务器。但是我看到其他网站这样做了,所以一定有办法。
【问题讨论】:
标签: javascript canvas file-upload