在 Python 请求中使用 POST 表单数据上传图像

新手上路,请多包涵

我正在使用微信 API ……在这里我必须使用此 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)

我无法发布数据

原文由 micheal 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1k
2 个回答

来自微信 api 文档:

 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)

文档: https ://docs.python-requests.org/en/master/user/quickstart/#post-a-multipart-encoded-file

原文由 kev 发布,翻译遵循 CC BY-SA 4.0 许可协议

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

客户端.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)

服务器.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()

原文由 Rachit Tayal 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题