Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: expected str, bytes or os.PathLike object, not ImageFieldFile

I am trying to upload a file to an another server. I am trying to do it like that:

 package = Package.objects.get(id=package_id)
 with open(package.logo_image.image, 'rb') as image_handle:
        image_data = bytes(image_handle.read())
        image = {
            'type': 'IMAGE',
            'data': image_data,
            'xsi_type': 'Image'
        }
        logo_image = media_service.upload(image)[0]

Field in a model:

image = models.ImageField(upload_to=generate_file_path, null=True, blank=True)

After trying to run this code I get:

with open(package.logo_image.image, 'rb') as image_handle: TypeError: expected str, bytes or os.PathLike object, not ImageFieldFile

Converting to str() does not help.

Is is possoble to open this file i binary mode? Thank you!

like image 307
paskalnikita Avatar asked Feb 25 '26 23:02

paskalnikita


1 Answers

You don't need to open the file at all. ImageField (and FileField) give you direct access to the underlying file object.

package = Package.objects.get(id=package_id)
image_data = bytes(package.logo_image.image.read())
like image 87
Daniel Roseman Avatar answered Feb 27 '26 14:02

Daniel Roseman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!