"消息":"必需的请求部分\'文件\'不存在"

时间:2017-06-28 06:09:58

标签: python python-2.7 rest file-upload postman

我想使用REST和python上传文件。我可以使用Postman来做到这一点。但是当我从Postman获取Python代码并尝试使用请求模块自己执行它时,我得到以下错误。请帮忙。

import requests

url = "https://url******"

payload = "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: 
form-data; name=\"file\"; filename=\"Path to file"\r\n\r\n\r\n------
WebKitFormBoundary7MA4YWxkTrZu0gW--"
headers = {
    'content-type': "multipart/form-data; boundary=----
WebKitFormBoundary7MA4YWxkTrZu0gW",
    'auth_token': auth_token,
    'cache-control': "no-cache",
}

response = requests.request("POST", url, data=payload, headers=headers, 
verify=False)

print(response.text)

>>> response.text
u'{"message":"Required request part \'file\' is not 
present","detailedMessage":"
","errorCode":-1,"httpStatus":500,"moreInfo":""}'

3 个答案:

答案 0 :(得分:0)

由于获取错误的数据,似乎您发布的服务器上出现错误。 我没有你发布的网址,所以我不知道正确的数据形式。 尝试阅读明确的参考资料将对您有所帮助。

答案 1 :(得分:0)

当我尝试从 insomnia 为类似请求生成 python 代码时遇到了同样的问题。我通过对我的 python 代码进行以下更改来修复它:

import requests

url = "https://url******"
files = { 'file': ('file.wav', open('/path/to/file.wav', "rb"), 'audio/wave') }
headers = { 'auth_token': auth_token }

response = requests.request("POST", url, files=files, headers=headers)

print(response.text)

此问题是由标头上的 'Content-Type': 'multipart/form-data; boundary=---- WebKitFormBoundary7MA4YWxkTrZu0gW' 设置引起的。当您使用 files 时,将不再需要此设置。

在我的情况下,文件是 wav 文件,可以相应地更改 mime 类型或完全删除(对我有用)。

答案 2 :(得分:0)

我在使用请求上传文件时遇到了同样的问题。

1.通过从标题中删除内容类型 2.不要在payload上做json.dumps

会解决问题。

import requests
file_path='/home/ubuntu/workspace/imagename.jpg'
file_name=os.path.basename(file_path)    
namew, extension = os.path.splitext(file_name)
type_dict = {'.pdf': 'application/pdf',
                 '.jpeg': 'image/jpeg',
                 '.png': 'image/png',
                 '.tiff': 'image/tiff', '.jpg': 'image/jpg'}        

url = "https://dev.example.com/upload"
filetype = type_dict.get(extension, 'application/octet-stream')

payload={}
files=[
    ('file',(file_name,open(file_path,'rb'),filetype))
]
headers = {
    'Authorization': 'Token',
    }

response = requests.request("POST", url, headers=headers, data=payload, files=files)