我正在使用 diff 函数从 set_contents_from_file()
等路径上传图像。但他们从路径中获取图像然后上传它们。有没有直接上传imageObject的函数直接从python代码上传?
最佳答案
是的,S3 接受通过特制且预先授权的 HTML POST 表单上传。您可以将这些表单包含在任何网页中,以允许您的网站访问者仅使用标准网络浏览器即可向您发送文件。
底线,创建这样的表单:
<html>
<head>
<title>S3 POST Form</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<form action="https://s3-bucket.s3.amazonaws.com/" method="post" enctype="multipart/form-data">
<input type="hidden" name="key" value="uploads/${filename}"> <input type="hidden" name="AWSAccessKeyId" value="YOUR_AWS_ACCESS_KEY">
<input type="hidden" name="acl" value="private">
<input type="hidden" name="success_action_redirect" value="http://localhost/">
<input type="hidden" name="policy" value="YOUR_POLICY_DOCUMENT_BASE64_ENCODED">
<input type="hidden" name="signature" value="YOUR_CALCULATED_SIGNATURE">
<input type="hidden" name="Content-Type" value="image/jpeg">
<!-- 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>
</body>
</html>
然后,添加策略文档
S3 POST forms include a policy document that authorizes the form and imposes limits on the files that can be uploaded. When S3 receives a file via a POST form, it will check the policy document and signature to confirm that the form was created by someone who is allowed to store files in the target S3 account.
{"expiration": "2009-01-01T00:00:00Z",
"conditions": [
{"bucket": "s3-bucket"},
["starts-with", "$key", "uploads/"],
{"acl": "private"},
{"success_action_redirect": "http://localhost/"},
["starts-with", "$Content-Type", ""],
["content-length-range", 0, 1048576]
]
}
最后,签署您的 POST 请求
To complete your S3 POST form, you must sign it to prove to S3 that you actually created the form. If you do not sign the form properly, or if someone else tries to modify your form after it has been signed, the service will be unable to authorize it and will reject the upload.
import base64
import hmac, hashlib
policy = base64.b64encode(policy_document)
signature = base64.b64encode(hmac.new(AWS_SECRET_ACCESS_KEY, policy, hashlib.sha1).digest())
关于python - 我可以直接在 s3 上上传图片而不保存在本地文件夹中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50583441/