Upload Image using POST form data in Python-requests

▼魔方 西西 提交于 2019-11-26 09:34:01

问题


I\'m working with wechat APIs ... here I\'ve to upload an image to wechat\'s server using this API http://admin.wechat.com/wiki/index.php?title=Transferring_Multimedia_Files

    url = \'http://file.api.wechat.com/cgi-bin/media/upload?access_token=%s&type=image\'%access_token
    files = {
        \'file\': (filename, open(filepath, \'rb\'),
        \'Content-Type\': \'image/jpeg\',
        \'Content-Length\': l
    }
    r = requests.post(url, files=files)

I\'m not able to post data


回答1:


From wechat api doc:

curl -F media=@test.jpg "http://file.api.wechat.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE"

Translate the command above to python:

import requests
url = 'http://file.api.wechat.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE'
files = {'media': open('test.jpg', 'rb')}
requests.post(url, files=files)



回答2:


I confronted similar issue when I wanted to post image file to a rest API from Python (Not wechat API though). The solution for me was to use 'data' parameter to post the file in binary data instead of 'files'. Requests API reference

data = open('your_image.png','rb').read()
r = requests.post(your_url,data=data)

Hope this works for your case.




回答3:


import requests

image_file_descriptor = open('test.jpg', 'rb')
filtes = {'media': image_file_descriptor}
url = '...'
requests.post(url, files=files)
image_file_descriptor.close()

Don't forget to close the descriptor, it prevents bugs: Is explicitly closing files important?




回答4:


For Rest API to upload images from host to host:

import urllib2
import requests

api_host = 'https://host.url.com/upload/'
headers = {'Content-Type' : 'image/jpeg'}
image_url = 'http://image.url.com/sample.jpeg'

img_file = urllib2.urlopen(image_url)

response = requests.post(api_host, data=img_file.read(), headers=headers, verify=False)

You can use option verify set to False to omit SSL verification for HTTPS requests.




回答5:


Use this snippet

import os
import requests
url = 'http://host:port/endpoint'
with open(path_img, 'rb') as img:
  name_img= os.path.basename(path_img)
  files= {'image': (name_img,img,'multipart/form-data',{'Expires': '0'}) }
  with requests.Session() as s:
    r = s.post(url,files=files)
    print(r.status_code)


来源:https://stackoverflow.com/questions/29104107/upload-image-using-post-form-data-in-python-requests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!