簡體   English   中英

使用jQuery驗證插件,輸入類型=文件未傳遞到PHP頁面

[英]Input type=file is not passing to php page using Jquery Validation Plugin

我有一個帶有文件上傳功能的html表單,我想使用jquery插件進行驗證。 現在,如果文件為空,則顯示錯誤消息,但是如果文件的擴展名不同,則應顯示消息“不允許文件類型”,但似乎沒有傳遞到文件filecheck.php頁面,該頁面將驗證文件類型。

如何使用此jquery插件驗證此文件類型? 你能幫我一下嗎? 謝謝。

HTML部分:

<div id="result"></div> <!--error or success message will be show here-->

<form action="editContactDetails.php" method="post" enctype="multipart/form-data" id="all_contact_details">
  <tr>
    <td></td>  
    <td align="left"><input name="file1" type="file" id="file" class="file"/></td>
    <td></td>
  </tr>
</form>

jQuery部分:

$(document).ready(function() {  
    // validate signup form on keyup and submit
    $("#all_contact_details").validate({
    submitHandler: function(form) {
        $.ajax({
            url: form.action,
            type: form.method,
            //async: false,
            data: $(form).serialize(),
            beforeSend : function (){
              $('input[type=submit]').attr('disabled', false); 
            },
            success: function(response) {
            $('#result').html(response);
            //$(form).find('div').hide();
            $(form).hide();

            }            
        });
    },

        rules: {            
            file1: {
                    required: true,                    
                    remote: {
                        url: "filecheck.php",
                        type: "post"
                     }
                },

        },
        messages: {         
            file1: {
                    required: "Upload your file",                    
                    remote: "File is not allowed"
                },          
        }
    });

});

PHP部分(filecheck.php)

<?php
$file1 =  $_FILES['file1']['name']; 
$allowedExts = array("jpg");    
$temp = stripslashes($file1);
$temp = explode(".", $temp);
$extension = end($temp);    

if(!in_array($extension, $allowedExts))
    echo 'false';
else
    echo 'true';        
?>

當表單有效時, SubmitHandler 處理實際的提交
http://jqueryvalidation.org/validate/#submithandler

因此,這不會驗證文件擴展名本身。

但是,您可以使用內置於jqueryvalidation的extension驗證器,該extension驗證器將完全執行您要達到的目標。 請參閱此鏈接以獲取參考和示例:

http://jqueryvalidation.org/extension-method/

在嘗試更多之前,並非所有瀏覽器都支持使用AJAX提交文件。 不過,您可以采取一些技巧,實際上是將表單提交到目標iframe,然后使用javascript讀取該iframe的內容並以某種方式顯示/使用它們。 這樣,您實際上提交了表單而不刷新主窗口。

本文對此進行了詳細介紹: Ajax:使用IFRAME的文件上傳表單的簡化版本

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM