Send file through POST without Content-Disposition in Python
Asked Answered
A

2

6

I am using requests in Python to send file over POST. My code looks like this:

headers = {'Content-Type': 'application/x-tar',                         
           'Content-Length': tar_size}

r = requests.post(server,                             
                  files={"file": (tar_name, open(tar_name, 'rb'))},         
                  headers=headers)  

On the same server from another client (written in C) files are send the same way. When the body_file (webob stuff see here http://docs.webob.org/en/stable/api/request.html) is read, from the C client the file is read, however from my client in Python the real file is prepened with:

--2a95cc93056b45e0b7c3447234788e29
Content-Disposition: form-data; name="file"; filename="filename.tar"

Is there some way to stop my client sending this stuff? Or some way how to fix server so it can read from C client and my client as well (even though it seems we send a little bit different messages)

Antemundane answered 19/4, 2017 at 15:49 Comment(2)
You mean you want to send just the bytes, nothing else? What about HTTP headers?Rhoads
It seems to me that multipart/form-data encoding does require that "Content-Disposition" stuff, so could it be that the C implementation is incorrect, or is defining a different protocol between your custom client and server? More useful info here: #8660308Rhoads
H
5

I had the same problem with unwanted Content-Disposition in the body of my POST. I solved it like this:

requests.post(server, headers=headers, data=open(myFile, 'rb').read())
Hadlock answered 28/8, 2019 at 0:13 Comment(0)
A
3

Ok, I was able to solve this. I will post my solution here if somebody has the same problem.

The solution was to use Prepared Requests (http://docs.python-requests.org/en/master/user/advanced/#prepared-requests) Then I could put the data into body in the form I needed. My code now looks like this:

headers = {'Content-Type': 'application/x-tar',                         
           'Content-Size': tar_size}
    
req = requests.Request('POST', server, headers)       

prepped = req.prepare()
with open(tar_name, 'rb') as f:
    prepped.body = f.read(tar_size)

s = Request.Session()  
r = s.send(prepped,
           stream=True)                              
            
Antemundane answered 20/4, 2017 at 6:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.