python文件上传错误“Required request part 'xxx' is not present”

背景:页面偶现上传文件失败,在研测环境都无法复现。于是想通过脚本来多次请求尝试复现问题。

查看请求信息:

开始撸码 (想当然的添加content-type和cookies)

import os
import requests

headers = {'Content-Type': 'multipart/form-data',
           'Cookie': 'access_token=eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiIxNzY4MTEwOTc1NyIsInNjb3BlIjpbIm9wZW5pZCJdLCJleHAiOjE2rpYATtO7g-AHopmAaeRfLuLi5SIsSZ0nl5ksAI_r-moPozyMQJh2vTt3p9Hc2_2tfJ7LVq0GU79XIgwBkPRZckoHgOUj39jO_aVLDd6iizp8fyuVBFLTQ'}

url = 'http://xxx.xxx.xxx/commonApi/kg/openqa/batch/import'
files = {'file': open(os.path.join(os.path.dirname(__file__), 'aee15f6befd14ed1979018bc03c9985a.xlsx'), 'rb')}
res = requests.post(url=url, files=files, headers=headers)
print(res.status_code)
print(res.json())

运行结果:

200
{'retcode': '999999', 'desc': "出现未知异常,错误信息为Required request part 'file' is not present"}

网上各种找资料,都没有对这种错误的解析,直到看到https://www.cnpython.com/qa/518198。。。

既然添加请求头的时候能想起来吧boundary去掉,为啥就没想起来这玩意加了令牌。。。

去掉Content-Type

import os
import requests

headers = {
    'Cookie': 'access_token=eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiIxNzY4MTEwOTc1NyIsInNjb3BlIjpbIm9wZW5pZCJdLCJleHAiOjE2MTEwNTExODUsImlhdCI6MTYxMDk2NDc4NSwiYXV0aG9yaXRpZXMiOlsiUk9MRV9BSU1JTkRfQURNSU5JU1RSQVRPUiJdLCJqdGkiOiJhY2FhNzIzYy1jN2Q3LTQ3YmQtYjI0Zi0zNTk3MWUyNDlmMjUiLCJjbGllbnRfaWQiOiJ3ZWJfYXBwIn0.SaYsEi0Z_bdEgARknWSKV2-ZUAxD4eNdLDd6iizp8fyuVBFLTQ'}

url = 'http://xxx.xxx.xxx/commonApi/kg/openqa/batch/import'
files = {'file': open(os.path.join(os.path.dirname(__file__), 'aee15f6befd14ed1979018bc03c9985a.xlsx'), 'rb')}
res = requests.post(url=url, files=files, headers=headers)
print(res.status_code)
print(res.json())

再次请求

200
{'retcode': '000000', 'desc': '成功'}
```![](https://img2020.cnblogs.com/blog/1638284/202101/1638284-20210118200650944-470169345.png)
posted @ 2021-01-18 20:07  唐大侠的小迷弟  阅读(5708)  评论(1编辑  收藏  举报