简体   繁体   English

如何在python中将图像传递给requests.post?

[英]How to pass image to requests.post in python?

Sorry Guys, I am new to Django, I am stuck with images upload.抱歉,伙计们,我是 Django 的新手,我一直在上传图片。

I have a REST_API for image upload.我有一个用于图像上传的 REST_API。 I pass the image and inside API get that image by using request.FILES['fileToUpload'] .我传递图像并在 API 内部使用request.FILES['fileToUpload']获取该图像。

Now I have an external API, which uploads an image on my behalf, that API is working fine on the postman.现在我有一个外部 API,它代表我上传图像,该 API 在邮递员上运行良好。

Here is the path of that API.这是该 API 的路径。

http://164.68.110.65/file_load.php http://164.68.110.65/file_load.php

But in Django.但是在姜戈。 I am not able to pass the image to this API.我无法将图像传递给此 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'] .你能告诉我,在 python 请求中,我们应该如何传递我的request.FILES['file_name_any']图像或文件。

Thanks.谢谢。 I will be very thankful for your favor.我将非常感谢您的青睐。

Your image is an UploadedFile or a TemporaryUploadedFile which is a subclass of File .您的imageUploadedFileTemporaryUploadedFile ,它是File的子类。 So you can just .open() it normally as any other File object:所以你可以像任何其他File对象一样正常地.open()它:

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.无需通过先保存文件来绕道而行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM