验证多个输入文件

验证多个输入文件

本文介绍了jQuery验证插件:验证多个输入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想问一下如何使用jQuery验证插件来验证多个文件输入.

I would like to ask how to validate multiple file input using the jQuery validation-plugin.

目前,我有以下代码,但它不起作用:

Currently I have these codes but it doesn't work:

.html:

<form id="uploadPhotoForm" enctype="multipart/form-data" method="POST">
    <table class= "uploadPhotoTable">
        <tr>
            <td>Photo</td>
            <td>:</td>
            <td><input class="field" type="file" name="files[]" id="upload_photo" align='right' multiple /></td>
        </tr>
    </table>
</form>

.js:

$('#uploadPhotoForm').validate({
    rules: {
      files: {
      required: true,
      extension: "png"
    }
    },
    messages:{
        files:{
           required : "Please upload atleast 1 photo",
           extension:"Only png file is allowed!"
        }
    }
  });

我还将使用此代码发布到新的PHP进行处理.但是似乎在我的uploadPhoto.php中,$_FILES['files']['tmp_name']是未定义的.我可以知道如何解决这个问题吗?

I also will use this code to post to new PHP for processing. But it seems like in my uploadPhoto.php, $_FILES['files']['tmp_name'] is undefined. May i know how to solve this?

if ($('#uploadPhotoForm').valid()) {
    $.ajax({
        url: "inc/uploadPhoto.php",
        type: "POST",
        data:  new FormData(this),
        contentType: false,
        cache: false,
        processData:false,
        success: function(data){
           $("#error1").html(data);
        }
    });
}

推荐答案

您需要'files[]'而不是files,并且如果您不添加 additional-methods.js ,您可以做到.

You need to 'files[]' instead of files, and if you doesn't add additional-methods.js, you will do it.

  $('#uploadPhotoForm').validate({
    rules: {
      'files[]': {
      required: true,
      extension: "png"
    }
    },
    messages:{
        'files[]':{
           required : "Please upload atleast 1 photo",
           extension:"Only png file is allowed!"
        }

    }

请参见 jsFiddle .

关于序列化.请阅读如何使用jquery序列化上传文件

About serialize.Please read this how to do file upload using jquery serialization

更新:

它将起作用

if ($('#uploadPhotoForm').valid()) {
    var form = $('#uploadPhotoForm')[0]; //  [0], because you need to use standart javascript object here
    var formData = new FormData(form);
    $.ajax({
        url: "inc/uploadPhoto.php",
        type: "POST",
        data:  formData,
        contentType: false,
        cache: false,
        processData:false,
        success: function(data){
           $("#error1").html(data);
        }
    });
}

我认为您的代码无效,因为data: new FormData(this),中的this无效的javascript表单对象.

Your code haven't work i think because this in data: new FormData(this), not valid javascript form object.

这篇关于jQuery验证插件:验证多个输入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 10:25