我想直接从HTML表单上传文件到S3而不先将其保存到服务器。我正在使用Boto3和Flask。 Flask和HTML代码发布在下面。我测试了与S3的连接,因此我的HTML表单存在问题。错误说"文件名必须是字符串"。谢谢你的帮助。
烧瓶中:
.route('/upload', methods=['GET', 'POST'])
@login_required
def upload():
try:
latestfile = request.form.get('filetoupload')
conn = boto3.client('s3', region_name="eu-west-1", endpoint_url="example.com", aws_access_key_id='the access key here', aws_secret_access_key='the secret key here',)
conn.create_bucket(Bucket="mytestbucket22")
bucket_name = "mytestbucket22"
conn.upload_file(latestfile, bucket_name, latestfile)
return render_template('dashboard.html', name=current_user.username, sumsg="Upload done!")
except Exception as ermsg:
print(ermsg)
return render_template('dashboard.html', name=current_user.username, ermsg=ermsg)
HTML:
<form action="./upload" method="post" enctype="multipart/form-data">
<input name="filetoupload" type="file">
<button type="submit" class="buttonformatting" onclick="showImage();">Download</button></a>
</form>
答案 0 :(得分:0)
从Flask请求获取上传文件后,您可以使用 conn.upload_fileobj()方法上传该文件。您现在正在使用 conn.upload_file(),它需要一个指向磁盘上文件的文件名。
执行类似
的操作file = request.files['filefield']
conn.upload_fileobj(file, 'mybucket', 'mykey')
更多文档和信息:
Flask请求对象为您提供 FileStorage 对象的行为类似于常规Python文件:http://flask.pocoo.org/docs/0.12/api/#flask.Request.files
在此处阅读Boto3文档:https://boto3.readthedocs.io/en/latest/reference/services/s3.html#S3.Client.upload_fileobj
答案 1 :(得分:0)
您需要构建一个带有签名策略的表单,如此处所述: https://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-post-example.html
您可以使用此Flask实用程序为您生成签名: https://github.com/fastmonkeys/pontus
从其网站上的示例中复制粘贴,以生成表单字段值: (取决于您将其以HTML格式放置):
import boto3
from flask import current_app
from pontus import AmazonS3SignedRequest
session = boto3.session.Session(
aws_access_key_id=current_app.config.get('AWS_ACCESS_KEY_ID'),
aws_secret_access_key=current_app.config.get('AWS_SECRET_ACCESS_KEY')
)
bucket = session.resource('s3').Bucket('testbucket')
signed_request = AmazonS3SignedRequest(
key_name=u'my/file.jpg',
mime_type=u'image/jpeg',
bucket=bucket,
session=session
)
signed_request.form_fields