1

Is there an easy way to upload single file using Python?
I know about requests, but it POST a dict of files containing a single file, so we have a little problem receiving that one file on the other end.

Currently code sending that file is:

def sendFileToWebService(filename, subpage):
    error = None
    files = {'file': open(filename, 'rb')}
    try:
        response = requests.post(WEBSERVICE_IP + subpage, files=files)
        data = json.load(response)
(...)

And the problem is that requests sends each file in a

--7163947ad8b44c91adaddbd22414aff8
Content-Disposition: form-data; name="file"; filename="filename.txt"
Content-Type: text/plain


<beggining of file content>
(...)
<end of file content>
--7163947ad8b44c91adaddbd22414aff8--

I suppose that's a package for a file. Is there a way to send file "clear"?

1 Answer 1

3

Use the data parameter to requests, not the files parameter:

def sendFileToWebService(filename, subpage):
    error = None
    try:
        response = requests.post(WEBSERVICE_IP + subpage,
                                 data=open(filename, 'rb'))
        data = json.load(response)
(...)

This will cause the file's contents to be placed in the body of the HTTP request. Specifying the files parameter triggers requests to switch to multipart/form-data.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.