python使用requests发文件上传请求,multipart/form-data数据
作者:互联网
python使用requests发文件上传请求,multipart/form-data数据
抓包获得的请求内容如下:
POST http://127.0.0.1:4444/file/upload/v1?userId=0000&password=er45fgwertewq5 HTTP/1.1
Host: 127.0.0.1
User-Agent: python-requests/2.25.0
Accept-Encoding: gzip, deflate
Accept: */*
Connection: keep-alive
Content-Type: multipart/form-data; boundary=c1685caf320946fb984c3ce32fdb6a62
other-keys: other-values
Content-Length: 597
--c1685caf320946fb984c3ce32fdb6a62
Content-Disposition: form-data; name="file"; filename="CICBLKCU2021042901.DAT"
Content-Type: application/DAT
156;;A8;123456;;A
156;0000008302892368;;123456;;A
156;0000001530849677;A8;123456;;
156;0000009999999999;A8;123456;;A
156;0000000113252271;A8;123456;;A
156;0000009317572450;A8;123456;2999-10-10;A
156;0000009336537481;A8;123456;;A
156;0000002969685091;A8;123456;;R
156;0000007556929507;A8;123456;;R
156;0000003817021175;A8;123456;;R
156;0000001576444332;A8;123456;;V
;0000003411358400;A8;123456;;A
--c1685caf320946fb984c3ce32fdb6a62--
其中文件内容为:
156;;A8;123456;;A
156;0000008302892368;;123456;;A
156;0000001530849677;A8;123456;;
156;0000009999999999;A8;123456;;A
156;0000000113252271;A8;123456;;A
156;0000009317572450;A8;123456;2999-10-10;A
156;0000009336537481;A8;123456;;A
156;0000002969685091;A8;123456;;R
156;0000007556929507;A8;123456;;R
156;0000003817021175;A8;123456;;R
156;0000001576444332;A8;123456;;V
;0000003411358400;A8;123456;;A
可以看到headers信息中的
Content-Type: multipart/form-data; boundary=c1685caf320946fb984c3ce32fdb6a62
其中格式要为multipart/form-data
–c1685caf320946fb984c3ce32fdb6a62 为分割符,内容不影响,随机生成
最后以 – 结尾
那我们要处理的就是吧文件内容转成格式为multipart/form-data的数据:
demo代码如下:
import requests
from requests_toolbelt import MultipartEncoder
upload_url = "http://127.0.0.1:4444/file/upload/v1?userId=0000&password=er45fgwertewq5"
filename = "test.DAT"
payload = {
'file': (filename, open(r'C:\test\{}'.format(filename), 'rb'), 'application/DAT')
}
m = MultipartEncoder(payload)
print(m)
headers = {
"Content-Type": m.content_type,
"other-keys": "other-values"
}
r = requests.post(upload_url, headers=headers, data=m)
print(r.json())
标签:form,156,python,发文件,multipart,A8,123456,data 来源: https://blog.csdn.net/weixin_45605401/article/details/116304939