一、文件上傳(Form 表單方式)【先將文件讀取至內存中,再將內存中的文件信息上傳至服務器】
1、單文件上傳
①文件上傳代碼,運行后logo.png文件上傳至服務器:
import requests files = {'file1': open('logo.png', 'rb')} response = requests.post('http://www.hangge.com/upload.php', files=files) print(response.text)
②顯式地設置文件名,文件類型和請求頭:
import requests files = {'file1': ('logo.png', # 文件名 open('logo.png', 'rb'), # 文件流 'image/png', # 請求頭Content-Type字段對應的值 {'Expires': '0'}) } response = requests.post('http://www.hangge.com/upload.php', files=files) print(response.text)
2、多文件上傳
①有時需要在一個請求中同時發送多個文件,同樣使用 files 參數傳入一個數組即可:
import requests files = [ ('file1', ('1.png', open('logo.png', 'rb'), 'image/png')), ('file2', ('2.png', open('logo.png', 'rb'), 'image/png')) ] response = requests.post('http://www.hangge.com/upload.php', files=files) print(response.text)
3、上傳文件時需要附帶其它參數
①如果我們需要在上傳文件的同時傳遞一些其它參數,也是可以的:
import requests data = { "name": "hangge.com", "age": 100 } files = [ ('file1', ('1.png', open('logo.png', 'rb'), 'image/png')), ('file2', ('2.png', open('logo.png', 'rb'), 'image/png')) ] response = requests.post('http://www.hangge.com/upload.php', data=data, files=files) print(response.text)
二、流式上傳文件【邊讀取文件邊上傳文件】
1、requests-toolbelt 擴展庫
①有時我們需要上傳一個非常大的文件(比如 1G 左右),如果像上面的方式直接使用 Requests 提交,可能會造成內存不足而崩潰。
②所以發送大文件時還是建議將請求做成數據流。不過默認情況下 Requests 不支持流式上傳,但有個第三方包 requests-toolbelt 是支持的(本質還是 multipart/form-data 上傳)
③ requests-toolbelt 是python請求的實用程序集合。
2、下載安裝 requests-toolbelt 第三方庫
pip install requests-toolbelt
3、使用流式上傳文件:
實例:使用 requests-toolbelt 來實現文件的流式上傳:
①不同於 requests 全部讀到內存中上傳, requests-toolbelt 是邊讀邊上傳。
②其本質還是 multipart/form-data 方式提交數據,所以服務端代碼不需要變化。
import requests from requests_toolbelt import MultipartEncoder # 邊讀取文件邊上傳文件 m = MultipartEncoder( fields={'name': 'logo.com', # 字段1 "age": '100', # 字段2 'file1': ('1.png', open('logo.png', 'rb'), 'image/png'), # 文件1 'file2': ('2.png', open('logo.png', 'rb'), 'image/png') # 文件2 } ) r = requests.post('http://www.hangge.com/upload.php', data=m, headers={'Content-Type': m.content_type}) print(r.text)
4、監聽上傳進度
① requests-toolbelt 庫 還提供了個監視器MultipartEncoderMonitor ,該監視器接受一個回調函數,我們可以在回調中實時跟蹤進度。
import requests from requests_toolbelt import MultipartEncoder, MultipartEncoderMonitor def my_callback(monitor): progress = (monitor.bytes_read / monitor.len) * 100 print("\r 文件上傳進度:%d%%(%d/%d)" % (progress, monitor.bytes_read, monitor.len), end=" ") e = MultipartEncoder( fields={'name': 'logo.com', # 參數1 "age": '100', # 參數2 'file1': ('1.png', open('logo.png', 'rb'), 'image/png'), # 文件1 'file2': ('2.png', open('logo.png', 'rb'), 'image/png') # 文件2 } ) m = MultipartEncoderMonitor(e, my_callback) r = requests.post('http://www.hangge.com/upload.php', data=m, headers={'Content-Type': m.content_type}) print(r.text)
②運行效果如下,可以看到提交過程中會實時顯示進度: