[英]AWS Content Type Settings in S3 Using Boto3
I am trying to upload a web page to an S3 bucket using Amazon's Boto3 SDK for Python.我正在尝试使用 Amazon 的Boto3 SDK for Python 将 web 页面上传到 S3 存储桶。
I am having trouble setting the Content-Type
.我无法设置
Content-Type
。 AWS keeps creating a new metadata key for Content-Type
in addition to the one I'm specifying using this code:除了我使用以下代码指定的密钥之外,AWS 还不断为
Content-Type
创建一个新的元数据密钥:
# Upload a new file
data = open('index.html', 'rb')
x = s3.Bucket('website.com').put_object(Key='index.html', Body=data)
x.put(Metadata={'Content-Type': 'text/html'})
Any guidance of how to set Content-Type
to text/html
would be greatly appreciated.任何有关如何将
Content-Type
设置为text/html
的指导将不胜感激。
Content-Type
isn't custom metadata, which is what Metadata
is used for. Content-Type
不是自定义元数据,而是Metadata
的用途。 It has its own property which can be set like this: 它有自己的属性,可以像这样设置:
bucket.put_object(Key='index.html', Body=data, ContentType='text/html')
Note: .put_object()
can set more than just Content-Type
. 注意:
.put_object()
可以设置的不仅仅是Content-Type
。 Check out the Boto3 documentation for the rest. 查看Boto3文档以了解其余部分。
You can also do it with the upload_file()
method and ExtraArgs
keyword (and set the permissions to World read as well): 您也可以使用
upload_file()
方法和ExtraArgs
关键字(并将权限设置为World read):
import boto3
s3 = boto3.resource('s3')
s3.meta.client.upload_file('source_file_name.html', 'my.bucket.com', 'aws_file_name.html', ExtraArgs={'ContentType': "application/json", 'ACL': "public-read"} )
Here, data
is an opened file, not its content: 这里,
data
是一个打开的文件,而不是它的内容:
# Upload a new file data = open('index.html', 'rb')
To read a (binary) file: 要读取(二进制)文件:
import io
with io.open("index.html", mode="rb") as fd:
data = fd.read()
It will be better that way. 这样会更好。
Eample using Boto3 (2022) - Use "ExtraArgs" parameter使用 Boto3 (2022)的示例 - 使用“ExtraArgs”参数
s3 = boto3.client('s3', aws_access_key_id = AWS_ACCESS_KEY_ID, aws_secret_access_key = AWS_SECRET_ACCESS_KEY, region_name = "us-east-1")
s3.upload_file(file_path, s3_bucket, file_name, ExtraArgs={'ContentType': "application/json"})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.