通过XMLHttpRequest将文件上传到Amazon S3 public

时间:2016-04-14 20:39:29

标签: amazon-web-services amazon-s3 xmlhttprequest

我正在尝试使用Amazon S3设置简单的JS图像上传。以下是我的代码。

JS

host = "https://s3.eu-central-1.amazonaws.com/my.bucket.url/";

uploadAttachment = function(attachment) {
  file = attachment.file;
  key = createStorageKey(file);
  form = new FormData;
  form.append("key", key);
  form.append("acl", "public-read");
  form.append("Content-Type", file.type);
  form.append("file", file);
  xhr = new XMLHttpRequest;
  xhr.open("PUT", host + key, true);
  // ...
  xhr.send(form);
};

createStorageKey = function(file) {
  var date, day, time;
  date = new Date;
  day = date.toISOString().slice(0, 10);
  time = date.getTime();
  return "s3/attachments/" + day + "/" + time + "-" + file.name;
};

S3 Bucket Policy

{
    "Version": "2008-10-17",
    "Statement": [
        {
            "Sid": "1",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:*",
            "Resource": "arn:aws:s3:::my.bucket.url/*"
        }
    ]
}

S3 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>
        <MaxAgeSeconds>3000</MaxAgeSeconds>
        <AllowedHeader>*</AllowedHeader>
    </CORSRule>
</CORSConfiguration>

一切正常,但上传的文件不公开。而且,我甚至无法从Web界面公开它们。我唯一能做的就是删除它们。我真的需要公开这些文件。

如果可能,我真的想在不使用任何访问密钥的情况下完成此任务。

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

我明白了。

<强> JS

  • host更改为my.bucket.s3.eu-central-1.amazonaws.com
  • xhr.open("POST", host, true)
  • 可能不相关,但我删除了acl参数。

<强> CORS:

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

S3 Bucket Policy :我刚删除它。

S3 Bucket Permissions Granted "Upload/Delete permissions to everyone