目前,我不知道为什么我尝试从s3照片中获取 5-8小时之前上传的图像时,为什么总是遇到CORS错误。如果我在 5-8小时内得到它仍然可以!! 这是我的s3 aws配置:
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<AllowedMethod>HEAD</AllowedMethod>
<AllowedMethod>POST</AllowedMethod>
<AllowedMethod>PUT</AllowedMethod>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>`
这是我尝试获取图像的javascript代码:
function getData(link){
var image = new Image();
// image.crossOrigin = 'use-credentials';
image.crossOrigin = 'anonymous';
// create an empty canvas element
var canvas = document.createElement("canvas"),
canvasContext = canvas.getContext("2d");
image.onload = function () {
//Set canvas size is same as the picture
canvas.width = image.width;
canvas.height = image.height;
// draw image into canvas element
canvasContext.drawImage(image, 0, 0, image.width, image.height);
// get canvas contents as a data URL (returns png format by default)
var dataURL = canvas.toDataURL();
document.getElementById("test").innerHTML = dataURL;
};
image.src = link;
}
getData("https://whammybar.s3.ap-southeast-1.amazonaws.com/duy-gmail-com/productImage/20181001/11bba32c-b276-47f4-b1fa-e87b53136bcc.jpg")
<span id="test"></span>
答案 0 :(得分:1)
问题不在于S3存储桶配置,而在于如何渲染图像。
如果打开图像link,您可以清楚地看到它可以访问。
您做错了什么,就是尝试在span
元素中渲染图像,这就是为什么在您的示例中它将图像数据显示为base64字符串。
只需将span
元素更改为img
元素,然后将img.src
设置为dataUrl
function getData(link){
var image = new Image();
// image.crossOrigin = 'use-credentials';
image.crossOrigin = 'anonymous';
// create an empty canvas element
var canvas = document.createElement("canvas"),
canvasContext = canvas.getContext("2d");
image.onload = function () {
//Set canvas size is same as the picture
canvas.width = image.width;
canvas.height = image.height;
// draw image into canvas element
canvasContext.drawImage(image, 0, 0, image.width, image.height);
// get canvas contents as a data URL (returns png format by default)
var dataURL = canvas.toDataURL();
document.getElementById("test").src = dataURL;
};
image.src = link;
}
getData("https://whammybar.s3.ap-southeast-1.amazonaws.com/duy-gmail-com/productImage/20181001/11bba32c-b276-47f4-b1fa-e87b53136bcc.jpg")
<img id="test">