【问题标题】:Direct upload to S3 with JavaScript not working使用 JavaScript 直接上传到 S3 不起作用
【发布时间】:2015-07-06 18:59:58
【问题描述】:
<!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>

【问题讨论】:

  • 您是否开启了存储桶日志记录?另外,您是否测试过存储桶策略?您可以使用具有相同键的 CLI 并确保其正常工作。
  • 此存储桶配置适用于我正在使用的 Rails 应用程序,因此我知道上述方法有效。我将尝试存储桶记录

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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-28
    • 1970-01-01
    • 2019-04-05
    • 1970-01-01
    • 2011-10-06
    • 2016-04-07
    • 2015-11-01
    相关资源
    最近更新 更多