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

9 Answers 9

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);
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! This data.files[index].error is exactly what I was trying to figure out (where was the error message being saved).
"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.
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

1 Comment

It would not work with uppercase extentions, i.e. file "myphoto.JPG" would be not valid
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.

2 Comments

this is better solution than accepted answer. Here you use validation rules of library instead of creating your own
This is a good answer since the plugin documentation never mention how to properly get error message and display it back.
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"}

3 Comments

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.
^^ not in IE8 or IE9, because it doesnt support the file api.
@Narretz Exactly. Thats the drawback I should have covered.
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);
    }
});

Comments

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

1 Comment

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...
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;
                    }
                });

Comments

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);
  }

2 Comments

This has nothing to do with op's question.
really? catching errors has nothing to do with the question "how do I get the error message"?
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

1 Comment

Even their example doesn't work- I can upload .jpg files larger than 999 KB. How embarrassing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.