托管在AWS >和托管的静态文件的不同类型的文件的正确内容类型是什么,如何通过boto3?<<<<
我使用upload_file方法:
import boto3
s3 = boto3.resource('s3')
bucket = s3.Bucket('allecijfers.nl')
bucket.upload_file('C:/Hugo/Sites/allecijfers/public/test/index.html', 'test/index.html', ExtraArgs={'ACL': 'public-read', 'ContentType': 'text/html'})
这对HTML文件效果很好。我最初忽略了导致文件下载的额外功能(可能是因为内容类型是二进制的?(。我发现此页面列出了几种内容类型,但我不确定如何应用它。
例如。CSS文件可能应使用'contentType':" text/css"上传。但是JS文件,index.xml等呢?以及如何以明智的方式做到这一点?仅供参考,这是我当前从Windows上传到AWS的脚本,这需要String.replace(" ","/"(,它可能也不是最聪明的?
for root, dirs, files in os.walk(local_root + local_dir):
for filename in files:
# construct the full local path
local_path = os.path.join(root, filename).replace("\","/")
# construct the full S3 path
relative_path = os.path.relpath(local_path, local_root)
s3_path = os.path.join(relative_path).replace("\","/")
bucket.upload_file(local_path, s3_path, ExtraArgs={'ACL': 'public-read', 'ContentType': 'text/html'})
我使用AWS CLI从同一源上载了我的完整雨果网站到同一S3桶,并且在没有指定内容类型的情况下可以完美地运行,这也可以通过Boto 3?
非常感谢您的帮助!
有一个python内置库,可以猜测模仿。
因此,您可以首先查找每个文件名。它是这样的工作:
import mimetypes
print(mimetypes.guess_type('filename.html'))
结果:
('text/html', None)
在您的代码中。对于Windows路径,我还稍微改善了您的代码的可移植性。现在,它将做同样的事情,但是可以通过查找将在任何路径中使用的平台特定分离器(os.path.sep
(来移植到Unix平台。
import boto3
import mimetypes
s3 = boto3.resource('s3')
bucket = s3.Bucket('allecijfers.nl')
for root, dirs, files in os.walk(local_root + local_dir):
for filename in files:
# construct the full local path (Not sure why you were converting to a
# unix path when you'd want this correctly as a windows path
local_path = os.path.join(root, filename)
# construct the full S3 path
relative_path = os.path.relpath(local_path, local_root)
s3_path = relative_path.replace(os.path.sep,"/")
# Get content type guess
content_type = mimetypes.guess_type(filename)[0]
bucket.upload_file(
File=local_path,
Bucket=bucket,
Key=s3_path,
ExtraArgs={'ACL': 'public-read', 'ContentType': content_type}
)