簡體   English   中英

S3 boto3 損壞文件

[英]S3 boto3 corrupts file

我有以下 function:

def upload_file(file_name, bucket, object_name=None):
    """Upload a file to an S3 bucket -> from aws docs

    :param file_name: File to upload
    :param bucket: Bucket to upload to
    :param object_name: S3 object name. If not specified then file_name is used
    :return: True if file was uploaded, else False
    """

    # If S3 object_name was not specified, use file_name
    if object_name is None:
        object_name = file_name

    # Upload the file
    s3_client = boto3.client('s3')
    try:
        response = s3_client.upload_file(file_name, bucket, object_name)
    except ClientError as e:
        logging.error(e)
        return False
    return True

我正在嘗試將 html 文件上傳到充當網絡服務器的 S3 存儲桶。 當我手動將 html 文件上傳到 S3 時,它按預期工作,並在我導航到 S3 存儲桶的 URL 時顯示頁面。

如果我使用上面的 function 以編程方式上傳文件,將不再托管 html 文件,我的瀏覽器將嘗試下載 XZ 文件。

我是否缺少參數或其他內容?

感謝@jarmod,我了解到我設置的內容類型不正確。

這是更新后的 function 以將 HTML 文件上傳為文本/html。

def upload_file(file_name, bucket, object_name=None):
    """Upload a file to an S3 bucket -> from aws docs

    :param file_name: File to upload
    :param bucket: Bucket to upload to
    :param object_name: S3 object name. If not specified then file_name is used
    :return: True if file was uploaded, else False
    """

    # If S3 object_name was not specified, use file_name
    if object_name is None:
        object_name = file_name

    # Upload the file
    s3_client = boto3.client('s3')
    try:
        response = s3_client.upload_file(file_name, bucket, object_name, ExtraArgs={'ContentType': "text/html"})
    except ClientError as e:
        logging.error(e)
        return False
    return True

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM