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>
An enctype attribute called multi-part/form-data is required in a HTML form to upload a file. Secondly we will be required to use the input tag of HTML and set it equal to “file”. This adds a upload button in addition to an input button in the form.
The post() method sends a POST request to the specified url. The post() method is used when you want to send some data to the server.
Run the Application by running “python multiplefilesupload.py”. Go to browser and type “http://localhost:5000”, you will see “upload files” in browser.
A few points :
data
parameter to submit other form fields ( 'dir', 'submit' ) 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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With