BBQuercus
BBQuercus

Reputation: 879

Send FileList to Flask backend?

I want to give the user the possibility to upload multiple files during multiple stages which will be processed in my flask backend upon uploading. Therefore I have a multiple file input form in my HTML:

<form action="/do-stuff" method="POST" enctype="multipart/form-data">
    <label id="file-uploader-label" for="file-uploader">Upload Files</label>
    <input id="file-uploader" type="file" name="file" accept="image/*" multiple="true" required>

    <button id="btn-upload" type="submit">Upload</button>
</form>

I display all files in a table (not shown above) and give the user the possibility to remove items from the file list as follows:

let fileList = new Array;
const fileUploader = this.document.getElementById('file-uploader');
let uniqueid = 1;

fileUploader.addEventListener('change', function () {

    for (let i = 0; i < fileUploader.files.length; i++) {
        let currFile = fileUploader.files[i];
        fileList[uniqueid] = currFile;

        // Removal and display code

        uniqueid++;
    }
});

This leaves me with the fileList of type "FileList" containing all desired files. Whenever I upload the file-uploader will only use the latest / most recently uploaded files and not all.

Having the complete list - is there a way in javascript to append to the files contained in the file-uploader or a workaround to pass the data to my flask backend (werkzeug.datastructures.FileStorage type)?

Thanks in advance :)

Upvotes: 0

Views: 1614

Answers (1)

jsurkont
jsurkont

Reputation: 26

Once you have a complete list of files that you want to upload, you can make a POST request from JavaScript to your Flask endpoint to store the files.

With a minimal form

<form id="form-files">
    <input id="file-input" type="file" multiple=true />
    <button type="submit">Submit</button>
</form>

You can intercept the form submit action and send the files to a Flask endpoint. The fileList array comes from your file upload/remove logic.

var formFiles = document.getElementById('form-files');

formFiles.addEventListener('submit', function(e) {
    e.preventDefault();
    var formData = new FormData();
    var request = new XMLHttpRequest();
    for (var i = 0; i < fileList.length; i++) {
        formData.append('files[]', fileList[i]);
    }
    request.open('POST', '/upload');
    request.send(formData);
});

Finally write a flask upload endpoint that processes (stores) the files.

@app.route("/upload", methods=["POST"])
def upload():
    uploaded_files = request.files.getlist("file[]")
    # Store files

Upvotes: 1

Related Questions