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>
2
  • Btw, you are not sending dir. r = requests.post(url, files=files, data={"dir": "/uploads/"}) Commented May 12, 2017 at 13:21
  • @OzgurVatansever I have added the data. But still no file is uploaded. Commented May 12, 2017 at 13:27

2 Answers 2

14

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)
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. It works now. It seems that I have the wrong url to upload the file.
Without passing the param 'headers', it will raise an error : werkzeug.exceptions.UnsupportedMediaType: 415 Unsupported Media Type: Did not attempt to load JSON data because the request Content-Type was not 'application/json'.
@stevezkw Yes, I think the Content-Type header is set to multipart/form-data automatically by requests. Which is what we want when uploading a file. But in your case you should probably use the json= parameter
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.

1 Comment

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.

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.