Search code examples
pythonpython-3.xboto3urllib3

Image file type is not supported when downloading using urllib3


hi I am downloading image like this

import urllib3     

http = urllib3.PoolManager()
r = http.request('GET', 'https://i.picsum.photos/id/192/536/354.png?hmac=a22QkdSZ7zXUHpV4-gnB48PPYaLlcvaTMeDXxcPRxs8')
print(r.data)

then uploading it to s3 using this

 s3 = boto3.resource(s3')
    key = 'file_name + '.png'    
    bucket = s3.Bucket(bucket_name)
    bucket.upload_fileobj(io.BytesIO(r.data), key) 

but when I open I get error on image opening "File type is not supported " when I open using photo opener

**EDIT:** I did as suggested by passing
 ContentType='text/png' 

and when I opening image by url getting this on aws : I opened this using presinged url

enter image description here


Solution

  • You did not actually mention how you add the ContentType. This is working example, using boto3.resource()

    bucketname = <my-bucket>
    filename   = <filename>
    
    s3 = boto3.resource('s3')
    key = 'image.png'
    bucket = s3.Bucket(bucketname)
    with open(filename, "rb") as fd:
        bucket.upload_fileobj(
            fd,
            Key=key,
            ExtraArgs={
                "ContentType": "image/png",
            }
        )
    

    I then generate a pre-signed URL (which you didn't include, but as long as you get the permissions right, I'm sure you're fine)

    expiration = 3600
    s3 = boto3.client('s3',
                      region_name='us-east-2',
                      config=boto3.session.Config(signature_version='s3v4'))
    response = s3.generate_presigned_url(
        'get_object',
        Params={
            'Bucket': bucketname,
            'Key': key
        },
        ExpiresIn=expiration
    )
    print(response)
    

    Opening the resulting URL in my browser, it loads the PNG image that I uploaded.