Upload files using Python and Flask

Spread the love

How to upload files using Python and Flask

 

In this tutorial we are going to learn, how to upload files using Python and flask framework. We will also upload multiple files. In a previous tutorial we explored How to join wav audio files using python – a beginner tutorial. Following steps are performed in this tutorial.

1. Python Installation

2. Create a project folder

3. Install flask framework

4. Create a templates folder

5. Create uploads folder to save files

6. Add CSS styles

7. Create a HTML  form to upload files using python

7. Create a Python script to upload a single file

5. Update python script to upload multiples file

upload files using pythonupload files using python

upload files using python and flaskupload files using python and flaskupload files using python and flask

Install Python

To install Python, Visit Download Python page and install on your system.

Create a project folder

Create project folder in a specified location, and name its upload_files_using_python and cd into the the folder by using command

cd upload_files_using_python

Install flask

Type command below to install flask.

pip install flask

Create a templates folder

Inside project folder create a folder named templates.

Create a uploads folder to save files

Create a folder uploads in project directory.

Add CSS styles

Add a folder css and a file style.css.  Add code below into it

body {
  color: #fff;
  background: #63738a;
  font-family: 'Roboto', sans-serif;
  }
  .form-control {
  height: 40px;
  box-shadow: none;
  color: #969fa4;
  }
  .form-control:focus {
  border-color: #5cb85c;
  }
  .form-control, .btn {        
  border-radius: 3px;
  }
  .signup-form {
  width: 450px;
  margin: 0 auto;
  padding: 30px 0;
  font-size: 15px;
  }
  .signup-form h2 {
  color: #636363;
  margin: 0 0 15px;
  position: relative;
  text-align: center;
  }
  .signup-form h2:before, .signup-form h2:after {
  content: "";
  height: 2px;
  width: 30%;
  background: #d4d4d4;
  position: absolute;
  top: 50%;
  z-index: 2;
  }  
  .signup-form h2:before {
  left: 0;
  }
  .signup-form h2:after {
  right: 0;
  }
  .signup-form .hint-text {
  color: #999;
  margin-bottom: 30px;
  text-align: center;
  }
  .signup-form form {
  color: #999;
  border-radius: 3px;
  margin-bottom: 15px;
  background: #f2f3f7;
  box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
  padding: 30px;
  }
  .signup-form .form-group {
  margin-bottom: 20px;
  }
  .signup-form input[type="checkbox"] {
  margin-top: 3px;
  }
  .signup-form .btn {        
  font-size: 16px;
  font-weight: bold;    
  min-width: 140px;
  outline: none !important;
  }
  .signup-form .row div:first-child {
  padding-right: 10px;
  }
  .signup-form .row div:last-child {
  padding-left: 10px;
  }      
  .signup-form a {
  color: #fff;
  text-decoration: underline;
  }
  .signup-form a:hover {
  text-decoration: none;
  }
  .signup-form form a {
  color: #5cb85c;
  text-decoration: none;
  }  
  .signup-form form a:hover {
  text-decoration: underline;
  }

Create a HTML form to upload files using python

Open templates folder and create a file upload.html, add code below into it.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:400,700">
<title>Upload images using Python and Flask</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="css/style.css">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
</head>
<body style="width: 50%; margin: 0 auto;">
    <div class="signup-form" style="margin-top: 50px;">
        <form method="post" action="/upload" enctype="multipart/form-data">
        <h5>Upload files using Python and Flask</h5>
        <div class="form-group">
            {% if msg %}
            <div class="alert alert-info" role="alert">
                <ul><li>{{ msg }}</li></ul>
            </div>
            {% endif %}
            <div class="ui-widget">
                <label for="tags">Upload File(s):</label>
                <input type="file" class="form-control" name="file" placeholder="select a file to upload" required>
                <br />
                <input type="submit" name="submit" class="btn btn-success btn-lg btn-block" value="Upload File(s)">
            </div>
        </div>
        </form>
    </div>
</body>
</html>

In the code above, a form is created with an input named file. There is an if condition to show msg from server. To upload a file to server, the enctype = “multipart/form-data” is added in the form.

upload files using python and flaskupload files using python and flaskupload files using python and flaskUpload a file using python script

After creating HTML form, add python code to upload file to server. Add a file upload.py in root project directory.

Directory named uploads is already created, where the uploaded files are saved.

from flask import Flask, render_template, request
import os

app = Flask(__name__)

app.config["UPLOAD_DIR"] = "uploads"
@app.route("/upload", methods = ["GET", "POST"])
def upload():
    if request.method == 'POST':
        file = request.files['file']
        file.save(os.path.join(app.config['UPLOAD_DIR'], file.filename))
        return render_template("upload.html", msg = "File uplaoded successfully.")

    return render_template("upload.html", msg = "")

if __name__ == "__main__":
    app.run()

First, flask, render_template, request and os modules are imported.

The flask constructor, takes name of current module.

app = Flask(__name__)

Next, the config is added for UPLOAD_DIR to save uploaded files. Upload route is added for GET and POST HTTP methods using @app.route method. The route will be /upload to access the server.

def upload():

The code below check that the data is posted using POST method. The uploaded file is assigned to file variable. The file is saved to the specified path. After file upload the html file is rendered using render_template and a success message is assigned.

if request.method == 'POST': 
   file = request.files['file'] 
   file.save(os.path.join(app.config['UPLOAD_DIR'], file.filename)) 
   return render_template("upload.html", msg = "File uplaoded successfully.")

When page is loaded first time the HTML file is rendered.

return render_template("upload.html", msg = "") 

if __name__ == "__main__":
   app.run()

The app.run executes the code in the file.

Run the application for upload files using python

Open command line, execute the command.

python upload.py

A message will be displayed.

Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

Open browser and add the URL in address bar.

http://127.0.0.1:5000

upload files using python and flask - success messageupload files using python and flask - success message

After file upload the success message is displayed.

Update python script to upload multiples file

To upload multiple file, add the parameter multiple to the input type = file.

<input type="file" class="form-control" name="file" placeholder="select a file to upload" required multiple>

Open upload.php file, and replace following code.

from flask import Flask, render_template, request
import os

app = Flask(__name__)

app.config["UPLOAD_DIR"] = "uploads"
@app.route("/upload", methods = ["GET", "POST"])
def upload():
    if request.method == 'POST':
        for file in request.files.getlist('file'):
             file.save(os.path.join(app.config['UPLOAD_DIR'], file.filename))
        return render_template("upload.html", msg = "File uplaoded successfully.")

    return render_template("upload.html", msg = "")

if __name__ == "__main__":
    app.run()

To upload multiple files a loop is added and getlist() method of request.files is added, each file is saved to the specified directory.

 

 

upload multiple files using python and flask - success messageupload multiple files using python and flask - success message

Source Code for the project

The source code of the tutorial is uploaded to the code repository. You can download or clone the repository.

upload files using python and flask - source codeupload files using python and flask - source code

Summary:

In this tutorial you learned about how to upload files using python and flask. HTML form and a Python script is added and updated to upload multiple files. The source code of tutorial can be found on GitHub repository.

Previous Article:

Next Article:

Related Articles:

 

 

Xổ số miền Bắc