blueImp/jquery file upload - How do I get the error message if the file type was not accepted?
Asked Answered
G

9

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

Gebler answered 20/9, 2012 at 5:19 Comment(0)
C
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

Cassiopeia answered 24/5, 2013 at 14:6 Comment(1)
It would not work with uppercase extentions, i.e. file "myphoto.JPG" would be not validLipsey
R
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);
});
Regularize answered 16/11, 2013 at 11:44 Comment(2)
Thank you! This data.files[index].error is exactly what I was trying to figure out (where was the error message being saved).Crippen
"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.Bitternut
C
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

Cassiopeia answered 24/5, 2013 at 14:6 Comment(1)
It would not work with uppercase extentions, i.e. file "myphoto.JPG" would be not validLipsey
J
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.

Jook answered 16/4, 2016 at 21:59 Comment(2)
this is better solution than accepted answer. Here you use validation rules of library instead of creating your ownAttalie
This is a good answer since the plugin documentation never mention how to properly get error message and display it back.Elul
M
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"}
Mousetrap answered 6/10, 2013 at 9:47 Comment(3)
This is not an efficient way to handle this, because you'll have to make unneccessary http requests even though you could handle it on the client.Holism
^^ not in IE8 or IE9, because it doesnt support the file api.Weinshienk
@Holism Exactly. Thats the drawback I should have covered.Mousetrap
S
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);
    }
});
Salpingitis answered 17/12, 2013 at 15:43 Comment(0)
M
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
Mnemonics answered 20/11, 2014 at 14:48 Comment(1)
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...Selfrestraint
L
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;
                    }
                });
Lipsey answered 9/2, 2016 at 23:14 Comment(0)
A
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);
  }
Aitch answered 15/2, 2013 at 19:39 Comment(2)
This has nothing to do with op's question.Stela
really? catching errors has nothing to do with the question "how do I get the error message"?Aitch
B
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

Behind answered 3/8, 2015 at 16:52 Comment(1)
Even their example doesn't work- I can upload .jpg files larger than 999 KB. How embarrassing.Stela

© 2022 - 2024 — McMap. All rights reserved.