美文网首页软件测试
Python上传文件

Python上传文件

作者: 卫青臣 | 来源:发表于2021-03-09 16:30 被阅读0次

通用方法,直接用即可,根据接口参数来写kwargs
requests-toolbelt是第三方包,支持发送大文件

import os
import requests
import filetype
from requests_toolbelt import MultipartEncoder

def upload_file(url, **kwargs):
    """
    :param kwargs 上传文件接口定义的参数
    """
    def get_filetype(file_path):
        file_type = filetype.guess(file_path)
        if file_type:
            return file_type.mime
        else:
            return "text/html"

    fields_dict = {}

    for param, value in kwargs.items():
        if os.path.isfile(value):
            file_name = os.path.basename(value)
            # 用二进制模式读取文件,因为requests会将文件的字节数设置为Content-Length,用文本模式可能会发生错误
            file_handler = open(value, 'rb')
            file_type = get_filetype(value)
            fields_dict[param] = (file_name, file_handler, file_type)
        else:
            fields_dict[param] = value

    encode_data = MultipartEncoder(fields=fields_dict)
    header = { 'Content-Type': encode_data.content_type }
    res = requests.post(url, headers=header, data=encode_data)
    return res.text


if __name__ == '__main__':
    # 接口只接收一个参数,参数名是multipartFile
    print(upload_file('https://xxx.com/upload', multipartFile='D://filepath'))

相关文章

网友评论

    本文标题:Python上传文件

    本文链接:https://www.haomeiwen.com/subject/crrbqltx.html