How to upload multiple files with Flask ?

Nelson Hernández
2 min readNov 16, 2020

--

In this example we will learn how to upload multiple files using Flask in a very simple way

upload multiple images with Flask || Nelsonher || nelsonher019

1) Creation of virtual environment

In this case I decided to use virtualenv but you can use pipenv if you like.

virtualenv venv
source ./venv/bin/activate

2) Installation of dependencies

pip install Flask

3 ) Flask server creation

from flask import Flaskapp = Flask(__name__)if __name__ == "__main__":
app.run(debug=True)

4) Endpoint upload multiple images

from flask import Flask, request
from werkzeug.utils import secure_filename
import os
app = Flask(__name__)@app.route('/upload/', methods=["POST"])
def upload_image():
if request.method == 'POST':
files = request.files.getlist("files")
for file in files:
filename = secure_filename(file.filename)
try:
working_directory = os.getcwd()
file.save(working_directory + "/files/" + filename)
except FileNotFoundError :
return 'Error, folder does not exist'
return "Success"
if __name__ == "__main__":
app.run(debug=True)

5) Frontend with JavaScript

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<input id="myInput" type="file" multiple />
<button type="click" id="btn">CLICK</button>
</body>
<script>
//CAPTURAMOS LA IMAGEN SELECCIONADA
const input = document.getElementById("myInput");
const btn = document.getElementById("btn");
var filenames = [];
var ficheros = null;
input.addEventListener("change", (e) => {
ficheros = e.target.files;
for (const iterator of e.target.files) {
filenames.push(iterator.filename);
}
});
btn.addEventListener("click", (e) => {
e.preventDefault();
// create formData object
const formdata = new FormData();
filenames.forEach((filename,index) => {
formdata.append("files", ficheros[index], filename);
});
var requestOptions = {
method: "POST",
body: formdata,
redirect: "follow",
};
fetch("http://localhost:5000/test", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
});
</script>
</html>

--

--