如何将图像传递给python中的request.post? [英] How to pass image to requests.post in python?
问题描述
对不起,我是Django的新手,我对图像上传感到困惑.
Sorry Guys, I am new to Django, I am stuck with images upload.
我有一个用于上传图片的REST_API.我传递图像,并在API内部通过使用获得该图像 request.FILES ['fileToUpload']
.
I have a REST_API for image upload. I pass the image and inside API get that image by using
request.FILES['fileToUpload']
.
现在,我有一个外部API,该API代表我上传了一个图像,该API在邮递员上正常工作.
Now I have an external API, which uploads an image on my behalf, that API is working fine on the postman.
这是该API的路径.
http://164.68.110.65/file_load.php
但是在Django中.我无法将图片传递给此API.我尝试了很多方法.
But in Django. I am not able to pass the image to this API. I have tried many ways.
像这些.
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.
您能否在python请求中告诉我,我们应该如何传递我的 request.FILES ['file_name_any']
中获得的图像或文件.
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.
推荐答案
您的 image
是 UploadedFile
或 TemporaryUploadedFile
是子类 File
.因此,您通常可以将 .open()
用作其他任何 File
对象:
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.
这篇关于如何将图像传递给python中的request.post?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!