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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 15:09:13  来源:igfitidea点击:

AWS Content Type Settings in S3 Using Boto3

pythonamazon-web-servicesamazon-s3

提问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-Typein 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-Typeto text/htmlwould be greatly appreciated.

如何设置任何指导Content-Type,以text/html将不胜感激。

采纳答案by Michael - sqlbot

Content-Typeisn't custommetadata, which is what Metadatais 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, datais 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 ExtraArgskeyword (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"} )