下载图像和上传时出现UnicodeDecodeError问题

时间:2016-11-14 13:50:40

标签: python python-3.x

尝试将下载的文件上传到s3时,我收到此错误:

# *** UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

我的理解是我的文件是以字节为单位,我不确定最终打开的是什么。我怎么能让这个工作好吗?

def download(url, file_name):
    with open(file_name, "wb") as file:
        response = requests.get(url)
        file.write(response.content)

def upload(cropped_img):
    s3_connection = boto.connect_s3()
    bucket = s3_connection.get_bucket(settings.AWS_S3_BUCKET_NAME)
    key = boto.s3.key.Key(bucket, 'th/' + cropped_img)
    with open(cropped_img) as f:
        key.send_file(f)

1 个答案:

答案 0 :(得分:1)

您必须以二进制模式打开文件:

with open(cropped_img, 'rb') as f:
    key.send_file(f)

或者,您可以使用boto.s3.key.Key.set_contents_from_filename()方法:

key.set_contents_from_filename(cropped_img)