Python 实现文件上传

原始的正确的文件下载接口:

最终实现的代码:

import json

import requests

url = 'https://test.jlcerp.com/faMaterialManage/fileInfo/uploadFile'
file_name = 'u4.png'
file_path = r'D:/Users/win10/Desktop/测试素材/u4.png'

files = [
    ('multipartFile',(file_name, open(file_path, 'rb'), 'image/png')),
    {'file', (file_name, open(file_path, 'rb'), 'image/png')}
]
header = {
    'Cookie': 'JSESSIONID=94FC918101F3C8FF018E0E6DD87CF232; erp_login_source=erp-portal; password=; is_remember_pwd=; sys_login_info={"loginTime":"2022-08-17 11:22:10","username":"adminkwt"}; username=adminkwt; JSESSIONID=8C27E1EF04AE3BCD9D1F73BD3BA35021; szjlc_back=FE31353416226DAFEE245C04F0D382C9.tomcat_jlc_back_1; newLogin=true; userAccount=adminkwt; userName=%u6D4B%u8BD5; XSRF-TOKEN=add59f29-7683-4792-8abb-c859420d6087; signature=b7185c0abc644bab8728130f729d7071; JLCWORK_SESSION_ID=836ad526-84c5-4ff0-b9d4-30316e83fe9f.tomcat_jlc_back_1',
    'X-XSRF-TOKEN': 'add59f29-7683-4792-8abb-c859420d6087',

}

proxies = {'https': 'http://127.0.0.1:8888'}
def upload_file(files, url, header, proxies):
    payload = {'fileType': '10','fileInfoCategory': '1', 'legalFileSuffixList': 'png,jpg,bmp,gif,pdf,jpeg,step,stp', 'file':'u4.png'}
    resp = requests.post(url, files=files, headers=header, data = payload, proxies= proxies, verify=False)
    print(resp.text)


if __name__ == '__main__':
    upload_file(files, url, header,proxies)

遇到的问题

问题1:fiddler 抓取不到 requests的包:

解决方式:己试
# 1.verify=False ,移除SSL验证
resp = requests.post(url, files=files, headers=header, data = payload, verify=False)
# 2.proxies= proxies, 需要和verify结合使用
proxies = {'https': 'http://127.0.0.1:8888'}
resp = requests.post(url, files=files, headers=header, data = payload, verify=False,proxies= proxies,)

问题2:requests.post 的files 参数如何传入多个值?

# 一开始的写法:
files ={'multipartFile': (file_name, open(file_path, 'rb'), 'image/png')}

导致一直是:

解决:

# file写为一个数组
files = [
    ('multipartFile',(file_name, open(file_path, 'rb'), 'image/png')),
    ('file', (file_name, open(file_path, 'rb'), 'image/png'))
]

总结:

  1. 表单的参数通过post方法的data参数传送
  2. files 第一个参数 要与上送表单的name值保持一致,如下

参考文章:

https://blog.csdn.net/m0_54850467/article/details/123220784
https://cloud.tencent.com/developer/article/1738147

posted @ 2022-10-26 18:24  chuangzhou  阅读(1803)  评论(0编辑  收藏  举报