0

I have Python flask webservice that takes in a file:

Headers:

Content-type: multipart/formdata

Content:

"fileTest": UPLOADED FILE

When I pass the file to another service using requests lib, I get issue where the uploaded file is not passed.

My Code:

files = {}
for form_file_param in request.files:
    fs = request.files[form_file_param]  # type: FileStorage
    files[form_file_param] = (fs.filename, fs.read())

req_headers = {
    "content-type": u "multipart/form-data; boundary=X-INSOMNIA-BOUNDARY",
}

r = requests.request(method='POST',
                     url=url,
                     headers=req_headers,
                     files=files)

I contact my other service directly through postman and it works successfully. I cannot seem to figure out what I am doing wrong in the above code.

NahinB
  • 1
  • 1

1 Answers1

0

You need to follow requests document.

http://docs.python-requests.org/en/master/user/quickstart/#post-a-multipart-encoded-file

url = 'https://httpbin.org/post'
files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}
r = requests.post(url, files=files)
r.text

Change . after watching OP response , the issue caused by header - Content-Type.

This is a special content type which can be visualized as multiple sub-requests in one big request. Each of those sub-requests (one form-data element) has their own set of headers. The content type of the actual data is in there.1

Note : there are no different between fs and fs.read()

#models.py line 149
if isinstance(fp, (str, bytes, bytearray)):
    fdata = fp
else:
    data = fp.read()
KC.
  • 2,981
  • 2
  • 12
  • 22
  • So I found the issue. `fs` is a filestorage object and not a file-like object which requests takes in. It has method called `fs.stream` that is a file-like object. I used that and I found that `boundary=X-INSOMNIA-BOUNDARY` in header was also causing the issue, so i removed it and it worked. Thanks none the less. – NahinB Oct 29 '18 at 15:23
  • `param files: (optional) Dictionary of ``'filename': file-like-objects`` for multipart encoding upload.` requests.request.__doc__ . also you can see how Content-Type create on models.py line 154 @NahinB – KC. Oct 30 '18 at 02:15