简体   繁体   中英

put_object into s3 boto3 gives a damaged file

I have a function that gets the video from S3 and does some operations on it (getting thumbnails and a short video from the original file).

I managed to download the file and do the operations. But when I try to upload it, it always gives me a damaged file. does anyone know the reason?

I'm using Python 3.6 and boto3.

My code:

thumb_img = './frames/0/40.png' #img thumb path
save_img = 'thumb_img_' + video_name.split('.')[0] + '.png'
session.put_object(ACL='public-read',
                   Body=thumb_img,
                   Key='PATH/TO/SUBFOLDER/' + save_img,
                   Bucket= BUCKET_NAME  )

Does anyone know why the file gets damaged?

The Body -attribute of the put_object call takes "bytes or seekable file-like object" as values according to the documentation , while you provide a file name.

The following code opens the file and provides the file descriptor as body instead:

thumb_img = './frames/0/40.png' # img thumb path
save_img = 'thumb_img_' + video_name.split('.')[0] + '.png'
with open(thumb_img, 'rb') as fd:
    session.put_object(ACL='public-read',
                       Body=fd,
                       Key='PATH/TO/SUBFOLDER/' + save_img,
                       Bucket=BUCKET_NAME)

So the issue was that I tried to upload a file directly. put_object takes bytes or seekable file-like object . So the solution was achieved with opening the file and taking the actual body of the file.

So the code:

   thumb_img = './frames/1/40.png' #img thumb path
    save_img = 'thumb_img_' + video_name.split('.')[0]+'.png'

    with open(thumb_img , 'rb') as fd:
        session.put_object(ACL='public-read',
                           Body=fd,
                           Key='PATH/TO/SUBFOLDER/' + save_img,
                           Bucket=BUCKET_NAME)

Thanks for the help..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM