代碼:html
Flask file uploadpython
$ curl -F 'file=@"foo.png";filename="bar.png"' 127.0.0.1:5000
注意:使用上傳文件功能的時候使用 POST form-data,參數名就是參數名(通常會提早約定好,而不是變化的文件名),參數的值是一個文件(這個文件正常是有文件名的)。git
有時候腳本生成了要上傳的文件,但並無留在本地的需求,因此使用臨時文件的方式,生成成功了就直接上傳。github
tempfile 會在系統的臨時目錄中建立文件,使用完了以後會自動刪除。flask
import requests import tempfile url = 'http://127.0.0.1:5000' temp = tempfile.NamedTemporaryFile(mode='w+', suffix='.txt') try: temp.write('Hello Temp!') temp.seek(0) files = {'file': temp} r = requests.post(url, files=files, proxies=proxies) finally: # Automatically cleans up the file temp.close()
或者直接使用 StringIO,能夠直接在內存中完成整個過程。app
import requests from StringIO import StringIO url = 'http://127.0.0.1:5000' temp = StringIO() temp.write('Hello Temp!') temp.seek(0) temp.name = 'hello-temp.txt' # StringIO 的實例沒有文件名,須要本身手動設置,不設置 POST 過去那邊的文件名會是 'file' files = {'file': temp} r = requests.post(url, files=files)
補上發現的一段能夠上傳多個同名附件的代碼:curl
files = [ ("attachments", (display_filename_1, open(filename1, 'rb'),'application/octet-stream')), ("attachments", (display_filename_2, open(filename2, 'rb'),'application/octet-stream')) ] r = requests.post(url, files=files, data=params)