Introduction

This example is about to upload multiple files using Python Flask REST API. We have also seen how to upload single file using Python Flask REST API. We may need to upload single or multiple files according to application’s requirements and here we are going to create an example on Python Flask REST API multiple files upload.

Prerequisites

Python 3.7.4, Flask 1.1.1

Creating Project Directory

Create a project root directory called python-flask-rest-api-multiple-files-upload as per your chosen location.

We may not mention the project’s root directory name in the subsequent sections but we will assume that we are creating files with respect to the project’s root directory.

Related Posts:

Configuring Application

We will configure application through flask framework. We will also define our file upload location and maximum size of all files a user can upload.

We should not allow user to upload unlimited size of file due to security reasons or to avoid exhausting server space.

Create a file called app.py with the below code.

from flask import Flask

UPLOAD_FOLDER = 'C:/uploads'

app = Flask(__name__)
#app.secret_key = "secret key"
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024

Configuring REST Endpoint

Now we will create REST endpoint that will be used to upload multiple files into the server.

We show a successful message once files uploaded successfully or error messages depending on the server error.

If partial file(s) are uploaded then we will see both success and error messages.

For success message message is the key in the JSON response.

For error messages file name is the key in the JSON response.

We define a method allowed_file(filename) to allow user only upload allowed file types.

Only with successful operation we send response status 201 otherwise we send 400 bad request with error message.

Create a file main.py with the below source code.

import os
import urllib.request
from app import app
from flask import Flask, request, redirect, jsonify
from werkzeug.utils import secure_filename

ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])

def allowed_file(filename):
	return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/multiple-files-upload', methods=['POST'])
def upload_file():
	# check if the post request has the file part
	if 'files[]' not in request.files:
		resp = jsonify({'message' : 'No file part in the request'})
		resp.status_code = 400
		return resp
	
	files = request.files.getlist('files[]')
	
	errors = {}
	success = False
	
	for file in files:		
		if file and allowed_file(file.filename):
			filename = secure_filename(file.filename)
			file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
			success = True
		else:
			errors[file.filename] = 'File type is not allowed'
	
	if success and errors:
		errors['message'] = 'File(s) successfully uploaded'
		resp = jsonify(errors)
		resp.status_code = 500
		return resp
	if success:
		resp = jsonify({'message' : 'Files successfully uploaded'})
		resp.status_code = 201
		return resp
	else:
		resp = jsonify(errors)
		resp.status_code = 500
		return resp

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

Deploying the Application

Now navigate to the project’s root directory using command line tool and execute the command python main.py, your server will be started on default port 5000.

If you want to change the port then you can change the line app.run() to app.run(port=5001), where 5001 is the new port.

Testing the Application

We will test our application using Postman tool. You may also do client side programming to call the above REST endpoint and upload the file.

Related Post:

Allowed File Types

When you upload allowed file types then you will see output similar to the below image.

I am uploading four pdf files here.

python flask rest api multiple files upload

Files uploaded in corresponding destination directory:

python flask rest api multiple files upload

Allowed and non-allowed File Types

I am uploading one pdf and one ppt files. So ppt did not get uploaded but pdf file.

python flask rest api multiple files upload

Pdf file uploaded in the destination folder:

python flask rest api multiple files upload

Non-allowed File Types

Here I selected exe and ppt files for uploading.

python flask rest api multiple files upload

That’s all.

Source Code

Thanks for reading.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *