7- How to Upload Files using Flask: A Beginner's Guide
Table of contents
No headings in the article.
If you're looking for a beginner's guide on how to upload files using Flask, you're in the right place! In this article, we'll show you how to upload files in Flask step-by-step, using an HTML file with "enctype=multipart/form-data" and a Python script with "GET" and "POST" methods. We'll also provide instructions on how to execute the script and access the upload page on a web browser. Whether you're new to Flask or just need a refresher, this guide will help you get started with file uploads in Flask.
Start by creating the upload.html file with the "enctype=multipart/form-data" attribute:
<html>
<body>
<form action = "http://localhost:5000/uploader" method = "POST"
enctype = "multipart/form-data">
<input type = "file" name = "file" />
<input type = 'submit'/>
</form>
</body>
</html>
Next, create the upload.py file with "GET" and "POST" methods and return "Upload succeeded" upon successful upload:
from flask import Flask, render_template, request
from werkzeug.utils import secure_filename
app = Flask(__name__)
@app.route('/upload')
def upload():
return render_template('upload.html')
@app.route('/uploader', methods=["GET", "POST"])
def uploader():
if request.method == 'POST':
f = request.files['file']
f.save(secure_filename(f.filename))
return ‘Upload succeeded.’
else:
return render_template('upload.html')
if __name__ == "__main__":
app.run(debug=True)
Execute the Python script by running the following command in your terminal:
python upload.py
To access the upload page on your web browser, navigate to:
You should see the following page:
Click on "Choose file" to select the file you want to upload, then click on the "Upload" button.
You should see the message "Upload succeeded" displayed on the page.
In conclusion, uploading files in Flask is a simple process that involves creating an HTML file with the "enctype=multipart/form-data" attribute and a Python script using "GET" and "POST" methods. The script should return "Upload succeeded" upon successful upload. This guide also provides steps to execute the Python script and access the upload page on a web browser.
* If you like the content, please SUBSCRIBE to my channel for the future content