【python-requests】实现文件上传

def upload_file(host, api,filepath, **kwargs):
    url = host + api
    querystring = {
        "app_id": "10000",
          "region": "en",
          "lang": "zh-cn"
    }
    headers = {
    }
    file_name = filepath.split("/")[-1]
    data = {
        "version": 1,
        "need_check": False,
        "operator": "123"
    }
    files = {"file": (file_name, open(filepath, 'rb'), "text/plain")}
    print(url)
    r = requests.post(url, params=querystring, headers=headers, data=data,files=files)
    return r.json()

上述方式支持multipart/form-data 方式,

坑:注意header里不要指定content-type类型,requests会自动生成,否则会报错

files里需要指定文件类型

text/plain
text/html
image/jpeg
image/png
audio/mpeg
audio/ogg
audio/*
video/mp4
application/*
application/json
application/javascript
application/ecmascript
application/octet-stream

具体文章:https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Basics_of_HTTP/MIME_types

你可能感兴趣的:(python)