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

blueimp, jquery

Solution

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

Problem

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

Original source