我可以直接在s3上上传图像而不保存在localfolder中吗?

2024-04-23 15:02:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用diff函数从set_contents_from_file()等路径上传图像。但他们从路径中获取图像然后上传。有没有函数可以直接上传imageObject直接上传python代码?你知道吗


Tags: 函数代码from图像路径contentsdifffile
1条回答
网友
1楼 · 发布于 2024-04-23 15:02:49

是的,S3接受通过精心编制和预先授权的HTML POST表单上传。您可以在任何网页中包含这些表单,以允许您的网站访问者只使用标准的web浏览器向您发送文件。你知道吗

看看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]
  ]
}

最后,签署你的发帖请求

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())

相关问题 更多 >