Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Sorry Guys, I am new to Django, I am stuck with images upload.

I have a REST_API for image upload. I pass the image and inside API get that image by using request.FILES['fileToUpload'].

Now I have an external API, which uploads an image on my behalf, that API is working fine on the postman.

Here is the path of that API.

http://164.68.110.65/file_load.php

But in Django. I am not able to pass the image to this API. I have tried many ways.

like these.

 image = request.FILES['fileToUpload']
 temp = Image.open(image)
 byte_io = BytesIO()
 temp.save(byte_io, 'png')
 files = {'fileToUpload': byte_io.getvalue() }
 response = requests.post( self.URL, files=files)
 print(response.status_code, response.content, response.reason)

but it always giving me an error that image format is not matched.

can you please tell me, in python-requests, how we should pass images or files that are got my request.FILES['file_name_any'].

Thanks. I will be very thankful for your favor.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
390 views
Welcome To Ask or Share your Answers For Others

1 Answer

Your image is an UploadedFile or a TemporaryUploadedFile which is a subclass of File. So you can just .open() it normally as any other File object:

with image.open('rb') as f:
    files = {'fileToUpload': f}
response = requests.post(self.URL, files=files)

No need to take the detour through saving the file first.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...