2016-09-16 161 views
2

我试图从浏览器上传数据到s3存储桶。我已经生成了预先签名的url,但是我得到了403禁止的回复。S3从浏览器上载带有预签名url的图片

我的服务器代码是

const s3 = new AWS.S3({ 
    accessKeyId: settings.resourceBucketKey, 
    secretAccessKey: settings.resourceBucketSecret, 
    region: 'eu-west-1' 
}) 

const params = { 
    Bucket: 'my-bucket', 
    Key: 'photo.png', 
    ContentType: 'image/png', 
    ACL: 'authenticated-read', 
} 

const url = s3.getSignedUrl('putObject', params) 

console.log(url) 

我的客户端代码(使用生成的URL)

const input = $('#myinput') 

     input.on('change', (res) => { 
     var theFormFile = $('#myinput').get()[0].files[0]; 

     $.ajax({ 
      url: url, 
      type: 'PUT', 
      contentType: 'image/png', 
      processData: false, 
      data: theFormFile, 
     }).success(function(){ 
      alert('success') 
     }) 
     }, false) 

我已经设置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>PUT</AllowedMethod> 
     <AllowedMethod>POST</AllowedMethod> 
     <AllowedHeader>*</AllowedHeader> 
    </CORSRule> 
</CORSConfiguration> 

但我的答复仍然被禁止。我想上传的图片叫'photo.png'。我在这里错过了什么吗?

回答

1

预签名URL的创建者(您)必须具有访问S3存储区才能上传文件的权限。这是多在S3 documentation雄辩地说明:

预标识的URL,您可以访问的URL标识的对象, 提供的预标识的URL的创建者有权 访问该对象。也就是说,如果您收到一个预先签名的URL以上传 对象,则只有在 预签名URL的创建者具有上载该对象所需的权限时,才能上传该对象。

确保创建预签名URL的IAM用户具有必要的权限。

+0

谢谢你正是这个问题! – wazzaday

0

完全实现从浏览器获取已签名的url - 享受!

<body> 
    <img height="200" width="200"> 
    <script> 

    var mimes = { 
     'jpeg': 'data:image/jpeg;base64,' 
    }; 

     AWS.config.update({ 
      signatureVersion: 'v4', 
      region: 'us-east-1', 
      accessKeyId: '', 
      secretAccessKey: '' 
     }); 

     var bucket = new AWS.S3({params: {Bucket: 'xxxx'}}); 

     function encode(data) 
     { 
      var str = data.reduce(function(a,b){ return a+String.fromCharCode(b) },''); 
      return btoa(str).replace(/.{76}(?=.)/g,'$&\n'); 
     } 

     function getUrlByFileName(fileName,mimeType) { 
      return new Promise(
       function (resolve, reject) { 
        bucket.getObject({Key: fileName}, function (err, file) { 
         var result = mimeType + encode(file.Body); 
         resolve(result) 
        }); 
       } 
     ); 
     } 

     function openInNewTab(url) { 
      var redirectWindow = window.open(url, '_blank'); 
      redirectWindow.location; 
     } 

     getUrlByFileName('sprites.png', mimes.jpeg).then(function(data) { 
      //openInNewTab(data); 
      document.querySelector('img').src = data; 
     }); 

    </script> 
</body> 
+0

不要忘记添加 -