在 Django 中只生成 s3 客户端 generate_presigned_post,内容类型用于 mp4 文件上传

问题描述

上传视频 (.mp4) 文件后,S3 元数据设置其Content-Type : binary/octet-stream 当我的浏览器强制下载文件而不是播放为了让它在浏览器中播放我需要改变那个内容类型以编程方式转换为 django

中的“video/mp4

解决方法

在花了很多时间之后,我找到了解决方案: {

def presign_post_S3_url(self,key=None,is_public=False):
    acl = 'private'

    if is_public:
        acl = 'public-read'
    fields = {"acl": acl,"Content-Type": "video/mp4"}
    conditions = [
        {"acl": acl},["starts-with","$Content-Type",""]
    ]
    if key is None:
        return ""
   ##s3_client is boto3.client object
    s3_client = self.get_s3_client()
    if s3_client is None:
        return ""
    data = s3_client.generate_presigned_post(
        Bucket=self.bucket,Key=key,Fields=fields,Conditions=conditions

    )
    return data