Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery file upload plugin: how to validate files on add?

$('#fileupload')
    .fileupload({
        acceptFileTypes: /(\.|\/)(jpg)$/i
    })
    .on('fileuploadadd', function (e, data) {
        console.log(data.files.valid); //undefined
        setTimeout(function () {
            console.log(data.files.valid); //true or false
        }, 500);
    })
;

jsFiddle

How to get boolean value of property data.files.valid without timeout ?

like image 673
cetver Avatar asked Mar 21 '13 13:03

cetver


People also ask

What is jQuery file upload?

Overview. jQuery Upload File plugin provides Multiple file Uploads with progress bar. Works with any server-side platform (Google App Engine, PHP, Python, Ruby on Rails, Java, etc.) that supports standard HTML form file uploads.


2 Answers

Here is what you want to do:

$('#fileupload')
    .fileupload({
        acceptFileTypes: /(\.|\/)(jpg)$/i
    })
    .bind('fileuploadadded', function (e, data) {
        console.log(data.files.valid);
    });

The core jquery.fileupload.js file is adding your files and triggering the "fileuploadadd" event, but that's before the files are validated.

The file jquery.fileupload-ui.js is doing the validation after the files are added, and triggering another "fileuploadadded" event once that's done.

Change the event, and you're all set.

Please Note:

This answer was valid and working as of March 2013 when it was posted. It appears that this upload plugin has changed since then. That means there is a new problem, and you should post a new question (or search to see if someone already has) rather than downvote this one!

like image 185
jszobody Avatar answered Nov 15 '22 09:11

jszobody


I think it can be possible using add method.

    var fileUploadInit = function() {
    $("#file-upload-form").fileupload({
        dataType: "json",
        url: url,
        add: function (e, data){
            if(validatefunction(data)){
                data.submit();
            } else {
                return false;
            }
        },
        progressall: function (e, data) {
            var progress = parseInt(data.loaded / data.total * 100, 10);
            $('#upload-progress').css('width',progress + '%');
        },
        done: function(e, data) {
            debugger
        },
        processfail: function(e, data){
            debugger
        }

    })
}
var validatefunction = function(data){
    // Do validation here. Return true if everything is correct else return                 false
}
like image 33
Dhruvil Amin Avatar answered Nov 15 '22 10:11

Dhruvil Amin