7- File Uploading in Flask
Play this article
Uploading files in Flask is very simple.
Start with creating upload.html file using "enctype=multipart/form-data":
<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>
Now create upload.py file using "GET" and "POST" methods and return "Upload succeeded":
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 with:
python upload.py
In your web brother go to:
http://localhost:5000/uploader
The following page should be opened:
Click on “Choose file” to select your file.
Then click on the “Submit” button.
You should see: “Upload succeeded”
* If you like the content, please SUBSCRIBE to my channel for the future content