我想链接下载S3存储的文件。
<a href="https://s3.region.amazonaws.com/bucket/file.txt" download>DownLoad</a>
它仅在浏览器上显示file.txt
。
所以我找到了下载方式。它是将Content-Disposition : attachment
元标记添加到文件。
但是我需要将此meta标签自动添加到新文件中。所以我用python制作了lambda function
。
import json
import urllib.parse
import boto3
print('Loading function')
s3 = boto3.client('s3')
def lambda_handler(event, context):
#print("Received event: " + json.dumps(event, indent=2))
# Get the object from the event and show its content type
bucket = event['Records'][0]['s3']['bucket']['name']
key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'], encoding='utf-8')
try:
response = s3.get_object(Bucket=bucket, Key=key)
print("CONTENT TYPE: " + response['ContentType'])
except Exception as e:
print(e)
print('Error getting object {} from bucket {}. Make sure they exist and your bucket is in the same region as this function.'.format(key, bucket))
raise e
try:
s3_2 = boto3.resource('s3')
s3_object = s3_2.Object(bucket, key)
print(s3_object.metadata)
s3_object.metadata.update({'ContentDisposition':'attachment'})
print(bucket, key)
s3_object.copy_from(CopySource={'Bucket':bucket, 'Key':key}, Metadata=s3_object.metadata, MetadataDirective='REPLACE')
except:
print(s3_object.metadata)
return response['ContentType']
但是此函数添加user defined metatag
而不是system metatag
。 。 。
我该怎么办?
答案 0 :(得分:1)
Content-Disposition
被S3视为(某种程度上)类似于系统元数据,而不是自定义/用户定义的元数据,因此它具有自己的参数。
s3_object.copy_from(CopySource={'Bucket':bucket, 'Key':key}, ContentDisposition='attachment', Metadata=s3_object.metadata, MetadataDirective='REPLACE')
请注意,您仍然需要如图所示的Metadata
和MetadataDirective
才能起作用,但是由于您没有更改自定义元数据,因此不需要s3_object.metadata.update()
。