在AWS S3中上载文件时指定最大文件大小

时间:2017-11-03 11:25:03

标签: amazon-web-services amazon-s3 aws-sts

我正在通过AWS Security Token Service(AWS STS)创建临时凭证。 并使用这些凭据将文件从S3 JAVA SDK上传到S3。 我需要一些方法来限制文件上传的大小。 我在创建用户时尝试添加策略(s3:content-length-range),但这似乎不起作用。 有没有其他方法来指定用户可以上传的最大文件大小?

2 个答案:

答案 0 :(得分:2)

另一种方法是生成预签名URL而不是临时凭证。对于具有您指定名称的文件,这将是一件好事。您还可以在生成URL时强制内容长度范围。您的用户将获得URL,并且必须使用特定方法(POST / PUT /等)来处理请求。他们在设置其他内容时设置了内容。

我不确定如何使用Java(它似乎没有条件支持),但Python and boto3很简单:< / p>

import boto3

# Get the service client
s3 = boto3.client('s3')

# Make sure everything posted is publicly readable
fields = {"acl": "private"}

# Ensure that the ACL isn't changed and restrict the user to a length
# between 10 and 100.
conditions = [
    {"acl": "private"},
    ["content-length-range", 10, 100]
]

# Generate the POST attributes
post = s3.generate_presigned_post(
    Bucket='bucket-name',
    Key='key-name',
    Fields=fields,
    Conditions=conditions
)

测试时,请确保每个标题项都匹配,否则您将获得模糊的访问拒绝错误。它可能需要一段时间才能完全匹配。

答案 1 :(得分:1)

我相信在上传之前无法限制对象大小,对此做出反应将非常困难。解决方法是创建一个S3 event notification,通过Lambda函数或SNS主题触发您的代码。例如,这可以验证或删除对象并通知用户。