S3 预签名 Post 需要特定的内容类型

S3 Presigned Post require specific Content-Type

首先,我使用的是 ruby 的 aws-sdk,但我面临的似乎是对 S3 预签名 posts 的误解。


我想要做的是确保使用我的预签名 post 上传到 S3 的任何内容都是视频。

我尝试做的是在 presigned_post 哈希中设置 content_type_starts_with: "video/"。这会导致所有上传都被拒绝 Policy Condition failed: ["starts-with", "$Content-Type", "video/"].

然后我只尝试 content_type: "video/mp4",但这会导致 s3 允许上传任何文件,然后在元数据中用 Content-Type: "video/mp4" 标记它。

然后我注意到,当我上传一个没有内容类型约束的文件时,S3 会将文件标记为 binary/octet-stream。所以我再次尝试了第一种方法,但这次使用 content_type_starts_with: "binary/"。结果与之前相同,Policy Condition Failed.

我应该如何使用 Content-Type 字段?它似乎从来没有按照我的意愿去做。


这是我正在使用的代码片段:

# In the controller

client = Aws::S3::Client.new(region: 'us-east-1')
resource = Aws::S3::Resource.new(client: client)
bucket = resource.bucket("my-bucket")

object_id = SecureRandom.uuid
object = bucket.object(object_id)

@presigned_post = object.presigned_post({
  acl: "private",
  content_length_range: 0..104857600, # 100 MB
  content_type_starts_with: "video/",
})

# In the presigned post erb

<form action="<%= presigned_post.url %>" method="post" enctype="multipart/form-data">
<% presigned_post.fields.each do |name, value| %>
    <input type="hidden" name="<%= name %>" value="<%= value %>"/>
<% end %>
    <input type="file" name="file" accept="*.mp4,*.ogg,video/*" />
    <input type="submit">
</form>

我刚刚遇到了一个非常相似的问题,我想我已经解决了。希望对您有所帮助。

我意识到设置 content_type_starts_with 实际上并没有限制上传的文件类型,但它限制了表单数据中 content-type 键的实际内容,但你仍然需要设置表单的内容类型 post.

由于我正在使用 JavaScript 进行客户端上传,因此我将其添加到我的上传代码中: formData.set('content-type', file.type) 其中 formData 是我最终通过 XMLHttpRequest 发送到服务器的 FormData 对象的一个​​实例。

执行此操作后,上传 pdf 将开始上传但不会将文件保存在 S3 上,因为 MIME 类型限制。

如果您需要更多信息,请告诉我,我基于我的一些上传代码:http://blog.teamtreehouse.com/uploading-files-ajax