无法在Ajax调用中将图像上载到AmazonS3

Cannot upload an image to Amazon S3 in Ajax call

本文关键字:图像 上载 AmazonS3 Ajax 调用      更新时间:2023-09-26

我试图在Ajax调用中将图像上传到AmazonS3,但出现了以下错误:

XmlHttpRequest无法加载https://bucketname.s3.amazonaws.com/.没有'访问控制-
请求的资源上存在Allow_Origin标头。因此,不允许访问源"null"。

我的JavaScript是这样的:

var xmlhttp = XmlHttpRequesr();    
var file = document.getElementById('file').files[0];        
var fd = new FormData();    
var key = "events/" + (new Date).getTime() + '-' + file.name;    
POLICY_JSON = {"expiration": "20020-01-01T00:00:00Z","conditions": [ {"bucket": "s3-bucket"}, 
["starts-with", "$key", ""], {"acl": "private"},{"success_action_redirect": "LOCALHOST"}, 
["starts-with", "$Content-Type", ""], ["content-length-range", 0, 1048576]  ] };    
var secret = this.get('key');    
var policyBase64 = window.btoa(JSON.stringify(POLICY_JSON));       
console.log ( policyBase64 );    
var signature = b64_hmac_sha1(secret, policyBase64);      
b64_hmac_sha1(secret, policyBase64);    
fd.append('key', 'uploads/${filename}');    
fd.append('acl', 'private');    
fd.append('Content-Type', file.type);    
fd.append('AWSAccessKeyId', key);    
fd.append('policy',  policyBase64);    
fd.append('signature',signature);    
fd.append("file",file);    xmlhttp.open('POST', Url, true);    xmlhttp.send(fd);    }

有人能帮我解决这个问题吗?

希望你已经有所收获。如果没有,我可以提供一点帮助。我刚开始使用AmazonS3,但我很清楚你需要设置访问控制设置。

https://console.aws.amazon.com/s3/home?region=us-东-1

然后点击你的水桶。然后单击"属性"。

您必须设置bucket策略和CORS策略。

我首先将bucket策略设置为admin,这允许我上传。然后计算出你想做什么所需要做的最低限度,这样你就不会敞开大门。

CORS政策也很重要。我担心我的太松了,不确定。但无论如何,它是有效的:

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
    <CORSRule>
        <AllowedOrigin>*</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <AllowedMethod>POST</AllowedMethod>
        <MaxAgeSeconds>3000</MaxAgeSeconds>
        <AllowedHeader>*</AllowedHeader>
    </CORSRule>
</CORSConfiguration>