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

Make files uploaded via XMLHttpRequest to Amazon S3 public

我正在尝试使用 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 存储桶策略:

{
    "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>

几乎一切正常,但上传的文件不是public。此外,我什至无法从 Web 界面设置它们 public。我唯一能做的就是删除它们。我真的需要这些文件 public.

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

非常感谢任何帮助!

我想通了。

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 存储桶策略:我刚刚删除了它。

S3 存储桶权限