Uploading images to a Flask server using FilePond (React component) Uploading images to a Flask server using FilePond (React component) flask flask

Uploading images to a Flask server using FilePond (React component)


Here's a proof of concept app that lets you upload multiple images using a form:

Note the enctype="multipart/form-data" attribute of the form, without this you cannot upload files.

Also note the multiple attribute of the file input. This allows client to select multiple files. You need to use request.files.getlist() to obtain the list of all uploaded files.

Once you generate the path to save the file, saving a werkzeug.FileStorage object is is just calling its .save(path_to_save) method.

from flask import Flask, request, render_template_string, redirect, abortfrom werkzeug import secure_filenamefrom pathlib import PathUPLOAD_DIR: Path = Path(__file__).parent / 'uploads'UPLOAD_DIR.mkdir(parents=True, exist_ok=True)app = Flask(__name__)def is_valid_upload(upload) -> bool:    # some validation logic    return Path(upload.filename).suffix.lower() in ['.jpg', '.jpeg']@app.route('/', methods=['GET', 'POST'])def upload():    html = '''        <form action='/' method='POST' enctype="multipart/form-data">            <input type="file" name='images' multiple>            <button>Upload</button>        </form>    '''    if request.method == 'GET':        return html    uploaded_files = request.files.getlist('images')    if not uploaded_files or not uploaded_files[0].filename:        return redirect('/')    valid_uploads = list(filter(is_valid_upload, uploaded_files))    if not valid_uploads:        return 'invalid image(s)', 400    for upload in valid_uploads:        filename = secure_filename(upload.filename)        save_path = str(UPLOAD_DIR / filename)        upload.save(save_path)    return 'uploaded'if __name__ == "__main__":    app.run()