The Wayback Machine - https://web.archive.org/web/20240913185945/https://www.geeksforgeeks.org/how-to-upload-file-in-python-flask/
Open In App

How to Upload File in Python-Flask

Last Updated : 07 Nov, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

File uploading is a typical task in web apps. Taking care of file upload in Flask is simple all we need is to have an HTML form with the encryption set to multipart/form information to publish the file into the URL. The server-side flask script brings the file from the request object utilizing the request.files[] Object. On effectively uploading the file, it is saved to the ideal location on the server.

Install the Flask by writing the command in terminal:

pip install flask

Stepwise Implementation

Step 1: A new folder “file uploading” should be created. Create the folders “templates” and “main.py” in that folder, which will store our HTML files and serve as the location for our Python code.

Step 2: For the front end, we must first develop an HTML file where the user can select a file and upload it by clicking the upload buttons. The user will click the submit button after choosing the file from their local computer in order to transmit it to the server.

Index.html

HTML




<html>  
<head>  
    <title>upload the file : GFG</title>  
</head>  
<body>  
    <form action = "/success" method = "post" enctype="multipart/form-data">  
        <input type="file" name="file" />  
        <input type = "submit" value="Upload">  
    </form>  
</body>  
</html>


Step 3: We must make another HTML file just for acknowledgment. Create a file inside the templates folder called “Acknowledgement.html” to do this. This will only be triggered if the file upload went smoothly. Here, the user will receive a confirmation.

Acknowledgement.html

HTML




<html>
   <head>
      <title>success</title>
   </head>
   <body>
      <p>File uploaded successfully</p>
      <p>File Name: {{name}}</p>
   </body>
</html>


Step 4: Now inside the ‘main.py’ write the following codes. The name of the objective file can be obtained by using the following code and then we will save the uploaded file to the root directory.

main.py

Python3




from distutils.log import debug
from fileinput import filename
from flask import *  
app = Flask(__name__)  
  
@app.route('/')  
def main():  
    return render_template("index.html")  
  
@app.route('/success', methods = ['POST'])  
def success():  
    if request.method == 'POST':  
        f = request.files['file']
        f.save(f.filename)  
        return render_template("Acknowledgement.html", name = f.filename)  
  
if __name__ == '__main__':  
    app.run(debug=True)


Output:

Run the following command in your terminal.

python main.py

 

 

Step 5: Now, to check if it is correctly working or not go to the folder where ‘main.py‘. Check in that folder you will find the files there.

Flask - File Upload

File structure



Previous Article
Next Article

Similar Reads

Upload and Read Excel File in Flask
In this article, we will look at how to read an Excel file in Flask. We will use the Python Pandas library to parse this excel data as HTML to make our job easier. Pandas additionally depend on openpyxl library to process Excel file formats. Before we begin, make sure that you have installed both Flask and Pandas libraries along with the openpyxl d
3 min read
How to use Flask-Session in Python Flask ?
Flask Session - Flask-Session is an extension for Flask that supports Server-side Session to your application.The Session is the time between the client logs in to the server and logs out of the server.The data that is required to be saved in the Session is stored in a temporary directory on the server.The data in the Session is stored on the top o
4 min read
Upload Multiple files with Flask
In online apps, uploading files is a common task. Simple HTML forms with encryption set to multipart/form information are all that is required to publish a file into a URL when using Flask for file upload. The file is obtained from the request object by the server-side flask script using the request. In this article, we will look at how to upload m
2 min read
Documenting Flask Endpoint using Flask-Autodoc
Documentation of endpoints is an essential task in web development and being able to apply it in different frameworks is always a utility. This article discusses how endpoints in Flask can be decorated to generate good documentation of them using the Flask-Autodoc module. This module provides the following features - Helps to document endpoints of
4 min read
How to Integrate Flask-Admin and Flask-Login
In order to merge the admin and login pages, we can utilize a short form or any other login method that only requires the username and password. This is known as integrating the admin page and Flask login since it simply redirects users to the admin page when they log in. Let's is how to implement this in this article. Integrate Flask Admin and Fla
8 min read
Minify HTML in Flask using Flask-Minify
Flask offers HTML rendering as output, it is usually desired that the output HTML should be concise and it serves the purpose as well. In this article, we would display minification of output routes of Flask responses using the library - Flask-Minify. Advantages of MinificationWebsites load faster as fewer lines are there to upload and download.Ban
12 min read
Flask URL Helper Function - Flask url_for()
In this article, we are going to learn about the flask url_for() function of the flask URL helper in Python. Flask is a straightforward, speedy, scalable library, used for building, compact web applications. It is a micro framework, that presents developers, useful tools, and, features, for coding REST APIs, and backend data processing, of web apps
11 min read
Upload file and read its content in cherrypy python
CherryPy is a web framework of Python which provides a friendly interface to the HTTP protocol for Python developers. It is also called a web application library. It allows developers to build web applications in much the same way they would build any other object-oriented Python program. This results in smaller source code developed in less time.
3 min read
Upload File With Selenium in Python
Uploading files using Selenium in Python allows developers to automate the process of interacting with file input elements on web pages. Leveraging the Selenium WebDriver, this tutorial guides users through the steps of locating file input elements, providing the file path for upload, and handling the submission process. What is Selenium?Selenium i
2 min read
File upload Fields in Serializers - Django REST Framework
In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Every serializer comes with some fields (entries) which are going to be processed. For example if you have a class with name Employee and its fields as Employee_id, Employee_name, is_admin, etc. Then, you would need AutoField
5 min read
Uploading and Reading a CSV File in Flask
Flask is a flexible, lightweight web-development framework built using python. A Flask application is a Python script that runs on a web server, which listens to HTTP requests and returns responses. It is designed for simple and faster development. In this article, let's upload a CSV (Comma-Separated Values) file and read the contents of the file o
3 min read
Read File Without Saving in Flask
Flask is a flexible, lightweight web-development framework built using python. A Flask application is a Python script that runs on a web server, which listens to HTTP requests and returns responses. It is designed for simple and faster development. In this article we will discuss how can we Read files without Saving them in Flask, we will also veri
2 min read
Upload and Download files from Google Drive storage using Python
In this article, we are going to see how can we download files from our Google Drive to our PC and upload files from our PC to Google Drive using its API in Python. It is a REST API that allows you to leverage Google Drive storage from within your app or program. So, let's go ahead and write a Python script to do that. Requirements: Python (2.6 or
6 min read
Upload files in Python
In this article, we will be looking into the process of file uploading in Python using cgi environment. One often comes across various web applications in which the client or the users is required to upload data in the form of a file(eg. image file, an audio file, text file, etc). There are two aspects to uploading a file, as there are two sides to
3 min read
How to Download and Upload Files in FTP Server using Python?
Prerequisite: FTP, ftplib Here, we will learn how to Download and Upload Files in FTP Server Using Python. Before we get started, first we will understand what is FTP. FTP(File Transfer Protocol) File Transfer Protocol(FTP) is an application layer protocol that moves files between local and remote file systems. It runs on the top of TCP, like HTTP.
3 min read
How To Upload And Download Files From AWS S3 Using Python?
Pre-requisite: AWS and S3 Amazon Web Services (AWS) offers on-demand cloud services which means it only charges on the services we use (pay-as-you-go pricing). AWS S3 is a cloud storage service from AWS. S3 stands for 'Simple Storage Service. It is scalable, cost-effective, simple, and secure. We generally store files in AmazonS3 in buckets. Bucket
3 min read
How to Upload Files Using Python Requests Library
We are given some files and our task is to upload it using request library of Python. In this article, we're going to discover a way to use the requests library to add files in diverse scenarios, such as uploading unmarried documents, multiple files, and documents with extra form statistics Upload Files Using Python Requests LibraryBelow, are the e
3 min read
Python Flask - ImmutableMultiDict
MultiDict is a sub-class of Dictionary that can contain multiple values for the same key, unlike normal Dictionaries. It is used because some form elements have multiple values for the same key and it saves the multiple values of a key in form of a list. Example: C/C++ Code from werkzeug.datastructures import MultiDict orders = MultiDict([(1, 'GFG'
2 min read
Python | Using for loop in Flask
Prerequisite: HTML Basics, Python Basics, Flask It is not possible to write front-end course every time user make changes in his/her profile. We use a template and it generates code according to the content. Flask is one of the web development frameworks written in Python. Through flask, a loop can be run in the HTML code using jinja template and a
3 min read
Subdomain in Flask | Python
Prerequisite: Introduction to Flask In this article, we will learn how to setup subdomains in Flask. But first, let's go through the basic like what is DNS and subdomains. Domain Name System (DNS): The Domain Name System (DNS) is a hierarchical and decentralized naming system for computers, services, or other resources connected to the Internet or
3 min read
Python | Build a REST API using Flask
Prerequisite: Introduction to Rest API REST stands for REpresentational State Transfer and is an architectural style used in modern web development. It defines a set or rules/constraints for a web application to send and receive data. In this article, we will build a REST API in Python using the Flask framework. Flask is a popular micro framework f
3 min read
Create a Weather app using Flask | Python
Prerequisite : Flask installation Flask is a lightweight framework written in Python. It is lightweight because it does not require particular tools or libraries and allow rapid web development. today we will create a weather app using flask as a web framework. this weather web app will provide current weather updates of cities searched. Basic setu
2 min read
Todo list app using Flask | Python
There are many frameworks that allow building your webpage using Python, like Django, flask, etc. Flask is a web application framework written in Python. Flask is based on WSGI(Web Server Gateway Interface) toolkit and Jinja2 template engine. Its modules and libraries that help the developer to write applications without writing the low-level codes
3 min read
Profile Application using Python Flask and MySQL
A framework is a code library that makes a developer's life easier when building web applications by providing reusable code for common operations. There are a number of frameworks for Python, including Flask, Tornado, Pyramid, and Django. Flask is a lightweight web application framework. It is classified as a micro-framework because it does not re
10 min read
How to Run Python Flask App Online using Ngrok?
Python Flask is a popular web framework for developing web applications, APIs, etc. Running flask apps on the local machine is very simple, but when it comes to sharing the app link to other users, you need to setup the whole app on another laptop. This article provides an interesting way to setup your web app online. Then, you can send the link to
2 min read
Create a Real Time Currency Converter app using Flask | Python
Prerequisite: installation of PythonWhat is Flask in Python ? Flask is a popular and lightweight Python web framework, meaning it is a third-party Python library used for developing web applications. Project Setup : create a new directory and name it 'CURRENCY-CONVERTER'. mkdir CURRENCY-CONVERTER &amp;&amp; cd CURRENCY-CONVERTER Inside it create tw
8 min read
Autocomplete input suggestion using Python and Flask
In this article, we will learn how to give features like auto-completion to the data that is passed from Flask. Autocomplete basically means predicting the rest of the word when the user types something. This way human interaction also increases with every correct prediction. Let's see how to do the same. We will be using jquery for autocompletion.
2 min read
Basic Validation using flask-gladiator module in Python
All kinds of validation are essential nowadays, considering all the unstructured data flowing in and out of systems. Apart from client-side validation, server-side validations are equally essential in web development. This article discusses a way in which validation can be injected in various frameworks such as Flask or Django. Python's flask-gladi
3 min read
Python Flask - Request Object
In a Flask App, we have our own Webpage (Client) and a Server. The Server should process the data. The Request, in Flask, is an object that contains all the data sent from the Client to Server. This data can be recovered using the GET/POST Methods. POST is used when your application expects user input to be received by command or an HTTP request, w
5 min read
Create GitHub API to fetch user profile image and number of repositories using Python and Flask
GitHub is where developers shape the future of software, together, contribute to the open-source community, manage Git repositories, etc. It is one of the most used tools by a developer and its profile is shared to showcase or let others contribute to its projects. Web Scraping using python is also one of the best methods to get data. In this artic
5 min read