Flying falcon
Flying falcon

Reputation: 133

"message":"Required request part \'file\' is not present"

I want to upload a file using REST and python. I am able to do it using Postman. But when I take the Python code from Postman and try to execute it on my own using requests module, I get the below error. Please help.

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":""}'

Upvotes: 1

Views: 1990

Answers (3)

Ramesh Ponnusamy
Ramesh Ponnusamy

Reputation: 1787

I have faced the same issue while upload files using requests.

1. By removing content type from headers 2. Don't do json.dumps on payload

will solve the problems.

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)

Upvotes: 1

Rohit Chaku
Rohit Chaku

Reputation: 47

I faced the same issue when I tried generating the python code from insomnia for a similar request. I fixed it by making the following changes to my python code:

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)

This problem is caused by 'Content-Type': 'multipart/form-data; boundary=---- WebKitFormBoundary7MA4YWxkTrZu0gW' setting on the header. When you use files this setting will no longer be necessary.

In my case the file was a wav file, the mime type can be changed accordingly or removed altogether (worked for me).

Upvotes: 1

Eric  Pwg
Eric Pwg

Reputation: 1

It seems that the error appear on the server you post to because of getting wrong data. I don't have the url you post to so i don't know the correct data form. Try to read the reference clearly will help you.

Upvotes: 0

Related Questions