Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python requests post a file

Using CURL I can post a file like

CURL -X POST -d "pxeconfig=`cat boot.txt`" https://ip:8443/tftp/syslinux

My file looks like

$ cat boot.txt
line 1
line 2
line 3

I am trying to achieve the same thing using requests module in python

r=requests.post(url, files={'pxeconfig': open('boot.txt','rb')})

When I open the file on server side, the file contains

{:filename=>"boot.txt", :type=>nil, :name=>"pxeconfig", 
:tempfile=>#<Tempfile:/tmp/RackMultipart20170405-19742-1cylrpm.txt>, 
:head=>"Content-Disposition: form-data; name=\"pxeconfig\"; 
filename=\"boot.txt\"\r\n"}

Please suggest how I can achieve this.

like image 978
user1191140 Avatar asked Apr 06 '17 06:04

user1191140


People also ask

How do I send a file with a POST request?

In the request body, click "form-data", hover over the "key" input field, and find the hidden dropdown that says "Text". Click "Text", and then change it to say "File". In the "Value" field, click "Select File" and select the file to send via the POST request body.

How do you send a POST request in Python?

To send a POST request using the Python Requests Library, you should call the requests. post() method and pass the target URL as the first parameter and the POST data with the data= parameter.

How do you upload a file in Python?

Method 1: Using the Python's os Module: Also, the enctype attribute with "multi-part/form-data" value will help the HTML form to upload a file. Lastly, we need the input tag with the filename attribute to upload the file we want. Lastly, we need the input tag with the filename attribute to upload the file we want.


1 Answers

Your curl request sends the file contents as form data, as opposed to an actual file! You probably want something like

with open('boot.txt', 'rb') as f:
    r = requests.post(url, data={'pxeconfig': f.read()})
like image 116
shad0w_wa1k3r Avatar answered Oct 29 '22 01:10

shad0w_wa1k3r