A simple file upload using Python’s Flask framework


 

What is Flask?

Flask is a micro web framework written using Python language, it uses Jinja for templating. Flask is very easy to get started with few lines of code.

Installing Flask

Create a folder where you want to have this app(Example: D:\flaskwebapp). Open the terminal window and CD to the created folder, run the below command to install the Flask web framework.

Writing code:

Create a folder called ‘templates’, then create a file ‘fileform.html’ inside the templates folder. Now, add the front end HTML form to upload a file in ‘fileform.html’.

then, create the pythong file ‘app.py’ inside the root folder of your app. Add the below lines of code to import the required modules.

this will load the created fileform.html, when you hit the home page, and add the below code to run the app.

Now, in terminal run this command “python app.py”, now the application will be running in localhost:5000, If we hit this URL, it will show the homepage with a simple file upload form.

The Backend part:

Let’s write the code to handle the upload by creating one more route.

this line of code is creating a route with path “/handleUpload” with acceptable HTTP method as POST. Add the below code to handle the file upload.

Now, restart the server, and try to upload a file. The file will be uploaded into “C:/Users/Public/Pictures”.

Complete app.py code:

Note: This is a very simple code to get started with file upload using Flask. In real case, it requires configurations for upload directory, file type and size validations. The complete code is available in GitHub.

You may also like

Sponsored

Follow me

Popular posts