python - 我可以直接在 s3 上上传图片而不保存在本地文件夹中吗?

标签 python amazon-web-services amazon-s3 boto3

我正在使用 diff 函数从 set_contents_from_file() 等路径上传图像。但他们从路径中获取图像然后上传它们。有没有直接上传imageObject的函数直接从python代码上传?

最佳答案

是的,S3 接受通过特制且预先授权的 HTML POST 表单上传。您可以将这些表单包含在任何网页中,以允许您的网站访问者仅使用标准网络浏览器即可向您发送文件。

看看 S3 POST Upload

底线,创建这样的表单:

<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/

相关文章:

python - 如果数据框列中的空值已存在于另一行中,则用相同的值填充该空值

python - 将一个张量变换为另一个张量

python - Go 中的 gRPC 服务器与 Python 中的客户端之间的兼容性

amazon-web-services - 是否可以使用 AWS Data Pipeline 将 RDS 数据库转储到 S3?

node.js - S3 正在将带有空格和符号的 url 编码为未知格式

python - 按下按钮时执行功能

node.js - 使用适用于 Java 的 AWS 开发工具包调用 AWS Lambda 函数时如何检索 context.done() 消息?

amazon-web-services - 云信息模板错误

java - 使用 Java 的 AWS Lambda 无法从 S3 获取文件

java - 没有访问 key /凭证的 AWS S3 Java 文件上传