Search code examples
jqueryfileuploadblueimp

How to make an AJAX call before blueimp uploader starts a multi-file upload


When multiple files are dropped onto a dropzone, I need to do a one-time server-side preparation before the individual files are uploaded.

Ideally, the uploader would have a multi-file-init callback that would allow me to make an ajax call to my server (where the preparation is done) and begin uploading of the individual files only when the preparation call returns.

Is there any way to achieve this end?

Currently, my server-side (php) code that is run for each uploaded file checks to see if the preparation has been done, and runs the preparation function if needed. But due to the uploader's asynchronously sending multiple files, a race-condition occurs and the prepartion function sometimes gets called multiple times.


Solution

  • I was able to solve my problem by following advice from barmar and adding a button to initiate uploads.

    I found specific instructions here: https://stackoverflow.com/a/38236305/671669

    I now include this code in the initialization of the blueimp jQuery-File-Upload plugin:

    add: function (e, data) {
        // enable the upload button
        $("#fileupload-start-button").prop('disabled', false);
    
        // wait for button click to process
        $("#fileupload-start-button").on('xyzUploadTrigger', function (e) {
            data.submit();
        });
    },
    

    And my binding to the "Start Upload" button looks like this:

    $("#fileupload-start-button").on('click', function (e) {
        $(this).prop('disabled', true)
        e.preventDefault();
    
        // prepare server-side for upload of resources
        axios.post('/resources/initResourceCollectionForUploader',
            {
                'params': params,
            })
            .then(function (response) {
                // hide the upload button and trigger it
                $("#fileupload-controls-container").addClass('d-none');
                $("#fileupload-start-button").trigger('xyzUploadTrigger');
            })
            .catch(function (error) {
                console.log(error);
            });
    });