使用JavaScript无法正常上传到S3

时间:2015-06-18 23:21:21

标签: javascript node.js amazon-web-services amazon-ec2 amazon-s3

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>s3</title>

  <script src="https://sdk.amazonaws.com/js/aws-sdk-2.1.34.min.js"></script>
<script type="text/javascript">
  // See the Configuring section to configure credentials in the SDK
  AWS.config.credentials = new AWS.Credentials({
    accessKeyId: 'MY ACCESS KEY', 
    secretAccessKey: 'MY SECRET KEY'
  });
  // Configure your region
  AWS.config.region = 'us-west-2';
</script>
</head>
<body>

<input type="file" id="file-chooser" /> 
<button id="upload-button">Upload to S3</button>
<div id="results"></div>

<script type="text/javascript">
  var bucket = new AWS.S3({params: {Bucket: 'MY BUCKET NAME'}});

  var fileChooser = document.getElementById('file-chooser');
  var button = document.getElementById('upload-button');
  var results = document.getElementById('results');
  button.addEventListener('click', function() {
    var file = fileChooser.files[0];
    if (file) {
      results.innerHTML = '';

      var params = {Key: file.name, ContentType: file.type, Body: file};
      bucket.upload(params, function (err, data) {
        results.innerHTML = err ? 'ERROR!' : 'UPLOADED.';
      });
    } else {
      results.innerHTML = 'Nothing to upload.';
    }
  }, false);
</script>

</body>
</html>

以上是我正在使用的代码,但是当我选择一个文件并上传它时,我在控制台上收到了这些错误:

MY_BUCKET_NAME.s3-us-west-2.amazonaws.com/burger.jpg:1 PUT https://MY_BUCKET_NAME.s3-us-west-2.amazonaws.com/burger.jpg 403(禁止)

奇怪的是......我以前正确地使用过S3,而且我通常会注意到在存储桶中创建了某种“嵌套结构”,而在上面,403发生在MY_BUCKET_NAME.s3- us-west-2.amazonaws.com/burger.jpg,它不是我习惯的嵌套结构。

我不知道出了什么问题。

这是我的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>
        <AllowedMethod>PUT</AllowedMethod>
        <MaxAgeSeconds>3000</MaxAgeSeconds>
        <ExposeHeader>ETag</ExposeHeader>
        <AllowedHeader>*</AllowedHeader>
    </CORSRule>
</CORSConfiguration>

1 个答案:

答案 0 :(得分:0)

我的秘密访问密钥缺少4个字符。