使用Python请求中的POST表单数据上载Image

时间:2015-03-17 16:08:34

标签: python python-3.x curl python-requests wechat

我正在使用微信API ... 在这里,我将使用此API将图像上传到wechat的服务器 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)

我无法发布数据

6 个答案:

答案 0 :(得分:36)

来自wechat api doc:

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

将上面的命令翻译成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)

答案 1 :(得分:3)

import requests

image_file_descriptor = open('test.jpg', 'rb')
url = '...'
requests.post(url, files=files)
image_file_descriptor.close()

别忘了关闭描述符,它可以防止错误:Is explicitly closing files important?

答案 2 :(得分:2)

当我想将图像文件从Python发布到rest API时遇到了类似的问题(虽然不是wechat API)。对我来说,解决方案是使用“数据”参数将文件发布为二进制数据而不是“文件”。 Requests API reference

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

希望这对您的情况有用。

答案 3 :(得分:2)

如果要将图像与其他属性一起作为JSON的一部分传递,则可以使用以下代码段。
client.py

import base64
import json                    

import requests

api = 'http://localhost:8080/test'
image_file = 'sample_image.png'

with open(image_file, "rb") as f:
    im_bytes = f.read()        
im_b64 = base64.b64encode(im_bytes).decode("utf8")

headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
  
payload = json.dumps({"image": im_b64, "other_key": "value"})
response = requests.post(api, data=payload, headers=headers)
try:
    data = response.json()     
    print(data)                
except requests.exceptions.RequestException:
    print(response.text)

server.py

import io
import json                    
import base64                  
import logging             
import numpy as np
from PIL import Image

from flask import Flask, request, jsonify, abort

app = Flask(__name__)          
app.logger.setLevel(logging.DEBUG)
  
  
@app.route("/test", methods=['POST'])
def test_method():         
    # print(request.json)      
    if not request.json or 'image' not in request.json: 
        abort(400)
             
    # get the base64 encoded string
    im_b64 = request.json['image']

    # convert it into bytes  
    img_bytes = base64.b64decode(im_b64.encode('utf-8'))

    # convert bytes data to PIL Image object
    img = Image.open(io.BytesIO(img_bytes))

    # PIL image object to numpy array
    img_arr = np.asarray(img)      
    print('img shape', img_arr.shape)

    # process your img_arr here    
    
    # access other keys of json
    # print(request.json['other_key'])

    result_dict = {'output': 'output_key'}
    return result_dict
  
  
def run_server_api():
    app.run(host='0.0.0.0', port=8080)
  
  
if __name__ == "__main__":     
    run_server_api()

答案 4 :(得分:1)

让Rest API在主机之间上传图像:

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)

您可以将选项验证设置为False,以省略HTTPS请求的SSL验证。

答案 5 :(得分:0)

使用此代码段

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)