我正在尝试使用JavaScript代码加载S3图片。但是它无法加载,并且在控制台上出现以下错误:
从源“ https://lcc-public-images.s3.amazonaws.com/”访问“ http://localhost:4200 {myFileName}”处的图像已被CORS策略阻止:所请求的资源上没有“ Access-Control-Allow-Origin”标头
public getImageDataUrlFromWebUrl(imageUrl: string): Observable<string> {
return Observable.create(observer => {
const image = new Image();
image.crossOrigin = "Anonymous";
// Image's base uri is localhost:4200
image.onload = () => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext("2d");
ctx.drawImage(image, 0, 0);
const dataURL = canvas.toDataURL('image/jpeg');
observer.next(dataURL);
};
image.onerror = () => {
observer.next('');//send empty dataUrl
}
image.src = imageUrl;// it is https://lcc-public-images.s3.amazonaws.com/{myFileName}
});
}
它出现在image.onError中。
以下是我的S3存储桶CORS设置:
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<AllowedMethod>POST</AllowedMethod>
<AllowedMethod>PUT</AllowedMethod>
<AllowedMethod>DELETE</AllowedMethod>
<MaxAgeSeconds>3000</MaxAgeSeconds>
<ExposeHeader>ETag</ExposeHeader>
<AllowedHeader>*</AllowedHeader>
</CORSRule>