Narender Yadav
Narender Yadav

Reputation: 19

Upload file using form-data body

I need to upload a PNG file using an API which says:

The request body accepts multipart/form-data with the key as uploadedFile.

Using Chrome postman plugin, I am able to upload the file using API, this is what I did:

Header: none
Body
  type: form-data
  key: uploadedFile
  Value: <file-location>
POST

This is the Python code that I have written:

login = requests.post(login_url, <other options>)
# above login is successful

upload_url = "Some_Value"
file_path = '/root/sample.png'
file = {'file': ('pngfile', open(file_path, 'rb'), 'image/png')}

body  = { 'uploadedFile':  file_path}

post_file = requests.post(upload_url, files=file, data=body,  cookies=login.cookies, verify=False)

I get the following error:

Bad Request[ errorCode:-18 ,message:Unsupported image file format. Please upload an image in GIF, JPEG or PNG format.]

Upvotes: 0

Views: 1260

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121486

You need to upload the file under the uploadedFile name. Do not use that name with a path, name the file itself that:

upload_url = "Some_Value"
file_path = '/root/sample.png'
file = {'uploadedFile': ('pngfile', open(file_path, 'rb'), 'image/png')}

post_file = requests.post(upload_url, files=file, cookies=login.cookies, verify=False)

POSTMan does the same thing; it takes the file location, loads the file data and sends the file data under the name uploadedFile.

You get the error message because by using uploadedFile in the data section, you sent a form-data section with no mimetype and binary data that is just a local file path string, not PNG or other image data. The file section is probably entirely ignored, because that's not the name the server is looking for.

Upvotes: 1

Related Questions