Flask – File Uploading
Handling file transfer in Flask is exceptionally simple. It needs a HTML structure with its enctype credit set to 'multipart/structure information', presenting the record on a URL. The URL handler gets file from request.files item and saves it to the ideal location.
Each transferred record is first spared in a brief area on the server, before it is really spared to its definitive area. Name of destination file can be hard-coded or can be acquired from filename property of request.files[file] object. Be that as it may, it is prescribed to acquire a protected form of it utilizing the secure_filename() function.
It is possible to characterize the way of default upload organizer and greatest size of transferred file in configuration settings of Flask object.
<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>
Click Submit after choosing file. Form’s post method invokes ‘/upload_file’ URL. The underlying function uploader() does the save operation.
Following is the Python code of Flask application.
from flask import Flask, render_template, request from werkzeug import secure_filename app = Flask(__name__) @app.route('/upload') def upload_file(): return render_template('upload.html') @app.route('/uploader', methods = ['GET', 'POST']) def upload_file(): if request.method == 'POST': f = request.files['file'] f.save(secure_filename(f.filename)) return 'file uploaded successfully' if __name__ == '__main__': app.run(debug = True)