Python S3 中使用 Boto3 的 AWS 内容类型设置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34550816/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
AWS Content Type Settings in S3 Using Boto3
提问by Rupert
I am trying to upload a web page to an S3 bucket using Amazon's Boto3 SDKfor Python.
我正在尝试使用 Amazon 的Boto3 SDKfor Python将网页上传到 S3 存储桶。
I am having trouble setting the Content-Type
. AWS keeps creating a new metadata key for Content-Type
in addition to the one I'm specifying using this code:
我在设置Content-Type
. Content-Type
除了我使用以下代码指定的元数据键之外,AWS还会继续创建新的元数据键:
# 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
将不胜感激。
采纳答案by Michael - sqlbot
Content-Type
isn't custommetadata, which is what Metadata
is used for. It has its own property which can be set like this:
Content-Type
不是自定义元数据,这Metadata
是用来做什么的。它有自己的属性,可以这样设置:
bucket.put_object(Key='index.html', Body=data, ContentType='text/html')
Note: .put_object()
can set more than just Content-Type
. Check out the Boto3 documentationfor the rest.
注意:.put_object()
可以设置的不仅仅是Content-Type
. 其余的请查看Boto3 文档。
回答by Laurent LAPORTE
Here, data
is an opened file, not its content:
这data
是一个打开的文件,而不是它的内容:
# Upload a new file data = open('index.html', 'rb')
# 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.
那样会更好。
回答by Jheasly
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"} )