28

I want to use the BlueImp/Jquery File Upload to be able to upload some images to web webserver. I have this JS code which I generated by reading many sources

 $('#file_upload').fileupload('option', {
        dataType: 'json',
        url: '/Upload/UploadFiles',
        maxFileSize: 5000000,
        acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
        process: [
            {
                action: 'load',
                fileTypes: /^image\/(gif|jpeg|png)$/,
                maxFileSize: 20000000 // 20MB
            },
            {
                action: 'resize',
                maxWidth: 1440,
                maxHeight: 900
            },
            {
                action: 'save'
            }
        ],
        progressall: function (e, data) {
            $(this).find('.progressbar').progressbar({ value: parseInt(data.loaded / data.total * 100, 10) });
        },
        done: function (e, data) {
            $('#show_image').append('<img src="' + data.result[0].ThumbURL + '" />');
            $('#imgID').val($('#imgID').val() + data.result[0].Id + ',');
            $(this).find('.progressbar').progressbar({ value: 100 });
        },
        error: function (e, data) {
            var a = 1;
        }
    });
});

It works because it doesn't upload any file which is not an image, but I would like to be able to get the error messages (in case it exists) to show to the user.

In their demo they have some code (jquery.fileupload-ui.js and jquery.fileupload-fp.js) that create "magically" the HTML with the error inside (I am still strugling to understand it).

I don't really get if I should use these plugins too and somehow customize the HTML being generated or if it is simpler to get the info manually and populate it.

I am pretty new to JS and Jquery, so maybe I am missing something.

How do I configure the HTML being generated or how do I get the error message?

Thanks, Oscar

JSBach
  • 4,679
  • 8
  • 51
  • 98

9 Answers9

35

I know this is an old thread, but if someone still looking for how to get the error message, here is a way to do it:

$('#fileupload').bind('fileuploadprocessfail', function (e, data) {
    alert(data.files[data.index].error);
});
user2999209
  • 359
  • 1
  • 3
  • 2
  • Thank you! This `data.files[index].error` is exactly what I was trying to figure out (where was the error message being saved). – nzifnab Feb 04 '14 at 19:00
  • 1
    "fail" will trigger only if webserver returns an error HTTP response. But "done" will be triggered also if your server upload handler returned error via "error" property. – Vladislav Rastrusny Oct 07 '14 at 11:30
16

For this you can use file added callback to validate files, like this, use "return false" to avoid adding that file;

 $('#yourfileuploader').fileupload({
                    add: function (e, data) {
                        var fileType = data.files[0].name.split('.').pop(), allowdtypes = 'jpeg,jpg,png,gif';
                        if (allowdtypes.indexOf(fileType) < 0) {
                            alert('Invalid file type, aborted');
                            return false;
                        }

                    }
                });

or you can register fileuploadadded callback like this,

$('#yourfileuploader').fileupload().bind('fileuploadadded', function (e, data) {
                    var fileType = data.files[0].name.split('.').pop(), allowdtypes = 'jpeg,jpg,png,gif';
                    if (allowdtypes.indexOf(fileType) < 0) {
                        alert('Invalid file type, aborted');
                        return false;
                    }
                });

also you can access fileupload acceptFileTypes options using; e.originalEvent.data.fileupload.options.acceptFileTypes

You can find more information here;

https://github.com/blueimp/jQuery-File-Upload/wiki/Options

SaminatorM
  • 630
  • 5
  • 18
14

As mentioned by user2999209, the right way to go is with the fileuploadprocessfail callback.

To complete his answer, if you wish to translate the error message you should pass the following (undocumented) option:

$('#my-uploader').fileupload({
    // ... some options ...
    messages : {
      maxNumberOfFiles: 'AAA Maximum number of files exceeded',
      acceptFileTypes: 'AAA File type not allowed',
      maxFileSize: 'AAA File is too large',
      minFileSize: 'AAA File is too small'
      uploadedBytes : 'AAA Uploaded bytes exceed file size'
    },
    // ... some other options ...
  })
  .on("fileuploadprocessfail", function(e, data) {
    var file = data.files[data.index];
    alert(file.error);
  });

Trying to upload a file with the wrong filetype will cause the message "AAA File type not allowed" to be displayed.

Jonathan Pasquier
  • 2,561
  • 1
  • 19
  • 17
  • this is better solution than accepted answer. Here you use validation rules of library instead of creating your own – Roman Yakoviv Jan 23 '18 at 08:58
  • This is a good answer since the plugin documentation never mention how to properly get error message and display it back. – ooi18 Oct 30 '19 at 03:14
6

If you are using a PHP server, I have a simpler solution. If you are not, I believe this might help you as well.

You don't need to use acceptFileTypes param in the frontend. Just initialize the PHP UploadHandler class with these params:

array(
    'accept_file_types' => '/\.(gif|jpe?g|png)$/i',
    'upload_url' => 'uploads/', // both of upload_url, upload_dir equals to the upload destination
    'upload_dir' => 'uploads/',
    'max_file_size' => 1024*1024*2 // in byte
)

When you pass undesired file type or file size, The ajax return will be something like

{name: "Dream Come True.mp3", size: 14949044, type: "audio/mp3", error: "File type not allowed"} 

or

{name: "feng (3).jpg", size: 634031, type: "image/jpeg", error: "File is too big"}
addlistener
  • 871
  • 1
  • 12
  • 20
5

Use the processfail callback

$('#fileupload').fileupload({
    maxFileSize: 5000000,
    done: function (e, data) {
        $.each(data.result.logo, function (index, file) {
            $('<p/>').text(file.name).appendTo('#fileupload-files');
        });
    },
    processfail: function (e, data) {
        alert(data.files[data.index].name + "\n" + data.files[data.index].error);
    }
});
Madhur
  • 2,119
  • 1
  • 24
  • 31
2

The order you load scripts is important to get the error message appear with default validation process,

This order works for me :

  1. tmpl.min.js
  2. jquery.ui.widget.js
  3. jquery.iframe-transport.js
  4. jquery.fileupload.js
  5. jquery.fileupload-ui.js
  6. jquery.fileupload-process.js
  7. jquery.fileupload-validate.js
FAjir
  • 4,384
  • 2
  • 26
  • 30
  • Can you provide some working example please, i can not realize default validation process. My script order is same. For some reason proccess events never has been triggered... – Vlatko Feb 20 '15 at 21:37
1

It would be better to validate file type (it would be format like "image/jpeg") than extention. In this case you avoid potential problem with case-sensitive and similar unexpected troubles

$('#yourfileuploader').fileupload().bind('fileuploadadded', function (e, data) {
                    var fileType = data.files[0].type;
                    if (type.indexOf('image') < 0) {
                        alert('Invalid file type, aborted');
                        return false;
                    }
                });
Oleg Sh
  • 8,496
  • 17
  • 89
  • 159
0

If you are new to understanding how javascript errorhandling works, it is best to read up on the topic: try/catch (MDN)

However, the error is actually a method within the fileupload prototype, so theoretically this function will execute when the error happens.

Just add {your code} to the errorHandler in the method.

...
error: function (e, data) {
        var a = 1; // <--in your example, this does nothing.
        alert(e); // <--or whatever you wish to do with the error
        return a; // <--did you want to return true?
    }
...

If this alert never happens, then no error is raised. The following code is normally how you catch them. (it doesn't do this already?)

try {

  ...any code you want to exception handle with...

  }
  catch (e) {      
    alert(e);
  }
Talvi Watia
  • 1,070
  • 1
  • 14
  • 28
0

Nothing I've found on in these answered worked for me, and strangely enough, the developers that wrote the demos for that plugin use a different style from whats described in the documentation. Anyway, that's aside from the point.

I copied the code they use to get the UI version to work, and that finally did the trick for me. They use the .on method and 'processalways' to check for errors instead of using an 'error' or 'fail' method.

view-source:http://blueimp.github.io/jQuery-File-Upload/basic-plus.html

Here's the source code.

Cheers

Nick Res
  • 2,154
  • 5
  • 30
  • 48