天天看點

【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