Search code examples
javascriptjqueryblueimp

BlueImp Jquery Upload - Get index from data.files


How do I get the index value from the following code?

add: function (e, data) {
    $.each(data.files, function (index, file) {
        alert('Added file: ' + index + " -- " + file.name);
});

The INDEX always return (0) even though I have (3) files. The FILE.NAME works and I am able to see all (3) files.

This was the output:

  • Added file: 0 -- dog.jpg
  • Added file: 0 -- cat.jpg
  • Added file: 0 -- honeybadger.jpg

This is what I was expecting/desired results to :

  • Added file: 0 -- dog.jpg
  • Added file: 1 -- cat.jpg
  • Added file: 2 -- honeybadger.jpg

After some debugging, it appears that the form is submitted (3) times which is why I get (0) for each file. Also, I have copied the code from the GIT WIKI but no luck.

Hoping a BlueImp expert can help out.

UPDATE CODE: The below code is now returning the each index

$('#fileUpload1').fileupload(
{
    replaceFileInput: false,
    dateType: 'json',
    url: 'Handlers/AjaxFileHandler.ashx',
    singleFileUploads: false,
    autoUpload: false,
    add: function (e, data) {
        $('#upLoadButton').click(function () {
            $.each(data.files, function (index, file) {
                alert('Added file: ' + index + " -- " + file.name);

                var v = $('input[data-id=' + index + ']').val();
                var d = $('select[data-id=' + index + ']').val();
                alert('textField:' + v + '  selected: ' + d);               
            });

            data.submit();

        });
    },
});

});

Solution

  • You are not correctly using the Add method function callback. In fact this event is fired by default for each single file. Data representing the file not the array of files. You need to set singleFileUploads to false in order to get what you want as in example below:

    $('#fileupload').fileupload({
            previewSourceMaxFileSize: 0,
            acceptFileTypes: /(\.|\/)(gif|jpe?g|png|bmp|svg|wmv|avi|mpe?g|mp4|ppt|pps)$/i,
            global:false,
            singleFileUploads:false, //set this to false to handle multi files upload behaviour
            add:function (e, data) {
                $.each(data.files, function (index, file) {
                    alert('Added file: ' + index + " -- " + file.name);
                });
            },
            autoUpload: false
        });