【问题标题】:How to pass image to requests.post in python?如何在python中将图像传递给requests.post?
【发布时间】:2019-12-26 21:26:23
【问题描述】:

对不起,伙计们,我是 Django 新手,图片上传卡住了。

我有一个用于图片上传的 REST_API。我通过图像和内部 API 通过使用获取该图像 request.FILES['fileToUpload'].

现在我有一个外部 API,它代表我上传图像,该 API 在邮递员上运行良好。

这是该 API 的路径。

http://164.68.110.65/file_load.php

但是在 Django 中。我无法将图像传递给此 API。我尝试了很多方法。

喜欢这些。

 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)

但它总是给我一个错误,图像格式不匹配。

你能告诉我,在 python-requests 中,我们应该如何传递我的request.FILES['file_name_any'] 获得的图像或文件。

谢谢。 非常感谢您的青睐。

【问题讨论】:

  • 我认为你必须在发送之前对图像进行base64编码
  • 这个答案可能对你有帮助:stackoverflow.com/a/45628257/3628578
  • 没有其他方法可以发送图像吗?像表单数据类型什么的。?
  • 怎么样with image.open('rb') as f: files = {'fileToUpload': f}; response = requests.post(self.URL, files=files)
  • 让我检查一下。

标签: python django python-3.x python-requests


【解决方案1】:

您的imageUploadedFileTemporaryUploadedFile,它是File 的子类。所以你可以像任何其他File 对象一样正常地使用.open()

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

无需先保存文件走弯路。

【讨论】:

    猜你喜欢
    • 2015-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-18
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多