11

I'm visiting a website and I want to upload a file.

I wrote the code in python:

import requests

url = 'http://example.com'
files = {'file': open('1.jpg', 'rb')}
r = requests.post(url, files=files)
print(r.content)

But it seems no file has been uploaded, and the page is the same as the initial one.

I wonder how I could upload a file.

The source code of that page:

<html><head><meta charset="utf-8" /></head>

<body>
<br><br>
Upload<br><br>
<form action="upload.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="hidden" name="dir" value="/uploads/" />
<input type="file" name="file" id="file" /> 
<br />
<input type="submit" name="submit" value="Submit" />
</form>

</body>
</html>
Ozgur Vatansever
  • 49,246
  • 17
  • 84
  • 119
Arolia
  • 511
  • 2
  • 6
  • 12

2 Answers2

13

A few points :

  • make sure to submit your request to the correct url ( the form 'action' )
  • use the data parameter to submit other form fields ( 'dir', 'submit' )
  • include the name of the file in files ( this is optional )

code :

import requests

url = 'http://example.com' + '/upload.php'
data = {'dir':'/uploads/', 'submit':'Submit'}
files = {'file':('1.jpg', open('1.jpg', 'rb'))}
r = requests.post(url, data=data, files=files)

print(r.content)
coffee-grinder
  • 26,940
  • 19
  • 56
  • 82
t.m.adam
  • 15,106
  • 3
  • 32
  • 52
3

First of all, define path of upload directory like,

app.config['UPLOAD_FOLDER'] = 'uploads/'

Then define file extension which allowed to upload like,

app.config['ALLOWED_EXTENSIONS'] = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])

Now suppose you call function to process upload file then you have to write code something like this,

# Route that will process the file upload
@app.route('/upload', methods=['POST'])
def upload():
    # Get the name of the uploaded file
    file = request.files['file']

    # Check if the file is one of the allowed types/extensions
    if file and allowed_file(file.filename):
        # Make the filename safe, remove unsupported chars
        filename = secure_filename(file.filename)

        # Move the file form the temporal folder to
        # the upload folder we setup
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

        # Redirect the user to the uploaded_file route, which
        # will basicaly show on the browser the uploaded file
        return redirect(url_for('YOUR REDIRECT FUNCTION NAME',filename=filename))

This way you can upload your file and store it in your located folder.

I hope this will help you.

Thanks.

Ahmed Ginani
  • 6,522
  • 2
  • 15
  • 33
  • Thanks for your reply. Actually, I am just visiting the website owned by others. I can upload the file through my browser, but I need to find a way to upload it through python. – Arolia May 12 '17 at 14:06