Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
392 views
in Technique[技术] by (71.8m points)

django - How to pass image to requests.post in python?

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...