上传文件amazon s3预签名帖子

时间:2015-06-05 13:59:49

标签: ruby-on-rails amazon-web-services amazon-s3

我正在开发一个网络应用程序,Id喜欢使用预先签名的帖子将文件上传到Amazon S3。按照此链接上的说明操作:http://aws.amazon.com/articles/1434我有以下表格。

<form action=<%= @aws_s3_url %> method="post" enctype="multipart/form-data">
      <input type="hidden" name="key" value= <%= @base_path + "${filename}" %> >
      <input type="hidden" name="AWSAccessKeyId" value= <%= @aws_access_key_id %> >
      <input type="hidden" name="acl" value="private">
      <input type="hidden" name="success_action_redirect" value=<%= "https://localhost:3000/projects/" + @project.id.to_s %> >
      <input type="hidden" name="policy" value= <%= @aws_policy %>>
      <input type="hidden" name="signature" value=<%= @aws_signature %>>
      <!-- Include any additional input fields here -->

      File to upload to S3:
      <input name="file" type="file">
      <br>
      <input type="submit" value="Upload File to S3">
    </form>

其中@aws_s3_url = "https://s3-eu-west-1.s3.amazonaws.com/my_bucket"

使用此方法生成策略:

def generate_policy_pre_signed_post(key)
  policy = "{ \"expiration\": \"#{Time.now.tomorrow.utc.iso8601}\","
  policy +="\"conditions\": ["
  policy += "{\"acl\": \"private\" },"
  policy += "{\"success_action_redirect\": \"https://localhost:3000/projects/#{@project.id.to_s}\"},"
  policy += "{\"bucket\": \"my_bucket\" },"
  policy += "[\"starts-with\", \"$key\", \"#{key}\"],]}"

  policy
end

然后在上面的链接中进行编码和签名:     policy = generate_policy_pre_signed_post(“/ users_data /”+ user_creds.aws_identity_id +“/”)

@aws_policy = Base64.encode64(policy).gsub("\n","")

@aws_signature = Base64.encode64(
  OpenSSL::HMAC.digest(
      OpenSSL::Digest::Digest.new('sha1'),
      server_credentials.secret_access_key, @aws_policy)
  ).gsub("\n","")

但是当我尝试将文件上传到S3时,它会出现以下错误:“不允许对此资源使用指定的方法。”

怎么会这样?在IAM中,我的用户拥有写入S3的所有权限,我也尝试过添加像这样的存储桶策略:

{
"Version": "2012-10-17",
"Statement": [
    {
        "Sid": "statement1",
        "Effect": "Allow",
        "Principal": {
            "AWS": "arn:aws:iam::my_iam"
        },
        "Action": [
            "s3:PutObject"
        ],
        "Resource": [
            "arn:aws:s3:::my_bucket/*"
        ]
    }
]
}

关于可能发生的事情的任何想法?

修改 香港专业教育学院也尝试修改CORS权限(它仍然无法正常工作)

<CORSRule>
    <AllowedOrigin>https://0.0.0.0:3000/*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>POST</AllowedMethod>
    <AllowedMethod>PUT</AllowedMethod>
    <MaxAgeSeconds>3000</MaxAgeSeconds>
    <AllowedHeader>*</AllowedHeader>
</CORSRule>

1 个答案:

答案 0 :(得分:0)

好的,我发现了!这真是愚蠢我在s3-eu-west-1.s3.amazonaws.com/my_bucket中有一个额外的s3,正确的方法是:s3-eu-west-1.amazonaws.com/my_bucket