Search code examples
jqueryfile-uploadblueimp

Sending an error or success message only after all files have been processed


I'm trying to send a success or error message in blueimp only once all the files are processed ... otherwise, the first file will send a success message and if another file has an error it will trigger the error as well.

Here is my code:

// Initialize the jQuery File Upload widget:
jQuery('#fileupload').fileupload({
    url: url, 
    done: function (e, data) {
        var response = jQuery.parseJSON( data.jqXHR.responseText );
        var error = response.files[0].error;

        if(error) {
            jQuery('#error').show();
            jQuery('#error').append('<p><strong>Error given:</strong> '+error+'</p>');
        } else {
            jQuery('#success').show();  
        }
    },
});

Thanks for any help!


Solution

  • When asking for help on github Sebastian Tschan, creator of blueimp jQuery-File-Upload, suggested that I try using the fileuploadstop method instead of singleFileUploads ... However, none of the blueimp stop methods have a data parameter, Here's how I was able to overcome this issue (thanks to a developer friend for his help):

    Javascript:

    // Using the Basic Plus UI version of the plugin ...
    
    // Global variables
    var status = new Array(), // Create a new array
        successAll = true; // Used to check for successful upload
    
    // After you've initialized the jQuery File Upload widget:
    jQuery('#fileupload') // Replace with your form id
        .bind('fileuploaddone', function (e, data) {
            // Append the file response data to the global array, in my case "status"   
            status.push( jQuery.parseJSON(data.jqXHR.responseText) );
        })
        .bind('fileuploadstop', function (e) {
            for (var i = 0; i < status.length; i++) {
                var error = status[i].files[0].error;
    
                if(error) {
                    jQuery('#error').show();
                    jQuery('#error').append('<p><em>Error given: '+error+'</em></p>');
    
                    successAll = false; // Change success value to false if error
                }
            }   
    
            // If successAll is true, meaning it wasn't reset because of an error,
            // display success message.
            if (successAll) {
                jQuery('#success').show();
            }   
            status = new Array();       
        });
    

    Works great! Hope it helps someone.