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

时间秒杀一切 提交于 2019-11-28 18:54:54

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!

I needed to do validation with a current version of the plugin (5.39.1) and this works for me:

Be sure to include jquery.fileupload-process.js and jquery.fileupload-validate.js in this order after jquery.fileupload.js and before your initializing script.

In your initializing script add the validation options and check validation in the fileuploadprocessalways callback:

$('.fileinput').fileupload({
    // The regular expression for allowed file types, matches
    // against either file type or file name:
    acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
    // The maximum allowed file size in bytes:
    maxFileSize: 10000000, // 10 MB
    // The minimum allowed file size in bytes:
    minFileSize: undefined, // No minimal file size
    // The limit of files to be uploaded:
    maxNumberOfFiles: 10
  }).on('fileuploadprocessalways', function (e, data) {
    var currentFile = data.files[data.index];
    if (data.files.error && currentFile.error) {
      // there was an error, do something about it
      console.log(currentFile.error);
    }
  });

All validations are optional, just don't leave the ones you don't need undefined.

This is what I did and it worked for me for newer versions: I created one validation per type of file and its size.

$("#fileUploadArea").fileupload({
        dataType: 'json',
        url:'${upload}',
        multiple:true,
        autoSubmit:false,
        maxNumberOfFiles: Number('${quantidadeMaximaArquivosUpload}'),
        dynamicFormData: function()
        {
            var data ={ 
                    idEntidadeEmpresarial: $('#idEntidadeEmpresarial').val(),
                    idDominioFamilia: $('#idDominioFamilia').val(),
                    idSubgrupo: $('select[id^="subgrupo_').map(function(){return $(this).val();}).get(),
                    descricao: $('#descricao').val(),
                    validade: $('#validade').val()
            }
            return data;
        },
        headers: {
            Accept: "application/json"
        },
        accept: 'application/json',        
        imageMaxWidth: 800,
        imageMaxHeight: 800,
        imageCrop: true ,
        stop: function(){
            $.unblockUI();
            if($('#fechar').is(":checked")){
                window.close();
            }else{
                $('select[id^="subgrupo_').each(function(){
                    $(this).val('');
                    $(this).trigger("chosen:updated");
                })
                $('#validade').val('');
                $('#descricao').val('');
                $('#sucesso').html('');
                $('#sucesso').append('<p><spring:message code="upload.sucesso"/>');
                $('#sucesso').show();
            }
        },
        error: function(files,status,errMsg)
        {
            $('#erro').html('');
            $('#erro').append('<p>'+errMsg+'</p>');
            $('#erro').show();
        },
        acceptFileTypes : ${listaExtensaoPermitidas}
    }).on('fileuploadprocessalways', function (e, data) {
        var currentFile = data.files[data.index];

        var tamanho = currentFile.size;
        var extensao = currentFile.name.substring(currentFile.name.lastIndexOf(".") +1,currentFile.name.length);            

        if(hashExtensao.get(extensao.toUpperCase()) < tamanho){
            alert("file type max size "+hashExtensao.get(extensao.toUpperCase());
            data.abort();
        }

    });
Nis

Well, the answer by @jszbody is the perfect answer.

However like myself in case if anyone lands here looking for solution to similar problem where user wants know if the file is not added correctly.

blueimp jquery-file-upload Doesn't throw error on unsuccessful add

This is what you want to do with the newer version of the plugin (9.11.2): Include this files:
- jquery.ui.widget.js
- jquery.iframe-transport.js
- jquery.fileupload.js
- jquery.fileupload-process.js
- jquery.fileupload-validate.js

$('#fileupload')
.fileupload({
    acceptFileTypes: /(\.|\/)(jpg)$/i
})
.on('fileuploadadd', function (e, data) {
    console.log('validation object not available at this point. Do not do submit here');
})
.on('fileuploadprocessalways', function (e, data) {
    console.log(data.files.error);//true if error
    console.log(data.files[0].error);//error message
    if(!data.files.error) data.submit(); //do submission here
});

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
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!