Upload Files using Python & Flask

How o upload files using Flask and Python

Uploading files is a regular job in web applications. You’ll learn how to achieve it with Python Flask in this tutorial. It’s quite easy to upload a file into a Flask web application using the Flask file.

To publish the file to the URL, you’ll need an HTML form with the enctype property set to “multipart/form-data.” To learn about HTML Forms you can click here.

The URL handler gets the file from the request.files [] object and saves it where it’s needed.

Upload file

Overview

Each uploaded file is saved to a temporary location on the server before being saved to its permanent location.

The target file’s name can be hard-coded or retrieved using the filename field of the file] request.files object. To obtain a safe version of it, however, the secure filename() function is advised.

In the Flask object’s configuration options, you can specify the default upload folder path and the maximum file size that can be uploaded.

Define the upload folder’s path.

app.config['UPLOAD_FOLDER']
Code language: CSS (css)

Sets the maximum file size (in bytes) that can be uploaded.

app.config['MAX_CONTENT_PATH']
Code language: CSS (css)

A ‘/upload’ URL rule displays’upload.html’ in the templates folder, and a ‘/upload – file’ URL rule invokes the upload () function to execute the upload procedure in the following code.

There are two buttons in ‘upload.html’: a file selector and a submit button.

<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>
Code language: HTML, XML (xml)

Python code

After you’ve chosen a file, click Submit. The ‘upload file’ URL is called by the form’s post method. A save action is performed by the underlying function uploader().

The Python code for the Flask application may be found here.

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)
Code language: JavaScript (javascript)

Conclusion

I hope you found this tutorial on how to upload files using Python and Flask useful. As always, If you have found this tutorial useful do not forget to share it and leave a comment if you have any questions. Happy Coding 🙂

%d bloggers like this: