requests python form-data 上传文件

"""
 @Coding: utf-8
 @Product: financial-huanqiu
 @Author: lyk
 @Time: 2019-02-28 10:30
 @FileName: zb_card_upload.py
 @Software: PyCharm
"""

import os
import traceback
import requests
import json
from utils.result_process import success,aborted

from requests_toolbelt.multipart.encoder import MultipartEncoder


#众邦身份证上传接口
async def post(app, request):
    params = request.json
    cur_file_path = os.path.dirname(os.path.realpath(__file__))
    before_phote = os.path.join(os.path.dirname(cur_file_path), params.get("before_idcard"))
    after_photo = os.path.join(os.path.dirname(cur_file_path), params.get("after_idcard"))
    before_filename = os.path.basename(before_phote)
    after_filename = os.path.basename(before_phote)
    fileList = [('fileList', (before_filename, open(before_phote, 'rb'), "image/jpeg")),
                ('fileList', (after_filename, open(after_photo, 'rb'), "image/jpeg"))]
    m = MultipartEncoder(fields=fileList, boundary="-------45962402127348")
    headers = {"content-type": m.content_type}
    url = 'http://api.fsp.dev.aitaigroup.com:8080/apiCliService/zbb/upload'
    try:
        res = requests.post(url, data = m,
                            headers = headers)
        result = json.loads(res.text)
        if result.get("respCode") == "0000":
            return success(result)
        else:
            return aborted(return_msg = result.get("respMsg"))
    except Exception as e:
        traceback.print_exc()


你可能感兴趣的:(requests python form-data 上传文件)