Ajax文件上传和表单上传自定义错误消息

时间:2018-11-28 11:55:58

标签: php html ajax

我正在按照本教程讲解如何使用ajax和php上传带有文件的图像。https://www.codexworld.com/ajax-file-upload-with-form-data-jquery-php-mysql/

一切正常,但由于某些原因,我收到了自定义错误消息 “发生了一些问题,请重试。”

即使上传文件和数据也是如此。

html

<p class="statusMsg"></p>
<form enctype="multipart/form-data" id="fupForm" >
<div class="form-group">
    <label for="name">NAME</label>
    <input type="text" class="form-control" id="name" name="name" placeholder="Enter name" required />
</div>
<div class="form-group">
  <label for="email">EMAIL</label>
    <input type="email" class="form-control" id="email" name="email" placeholder="Enter email" required />
</div>
<div class="form-group">
    <label for="file">File</label>
    <input type="file" class="form-control" id="file" name="file" required />
</div>
<input type="submit" name="submit" class="btn btn-danger submitBtn" value="SAVE"/>

Ajax

<script>
$(document).ready(function(e){
    $("#fupForm").on('submit', function(e){
        e.preventDefault();
        $.ajax({
            type: 'POST',
            url: 'submit.php',
            data: new FormData(this),
            contentType: false,
            cache: false,
            processData:false,
            beforeSend: function(){
                $('.submitBtn').attr("disabled","disabled");
                $('#fupForm').css("opacity",".5");
            },
            success: function(msg){
                $('.statusMsg').html('');
                if(msg == 'ok'){
                    $('#fupForm')[0].reset();
                    $('.statusMsg').html('<span style="font-size:18px;color:#34A853">Form data submitted successfully.</span>');
                }else{
                    $('.statusMsg').html('<span style="font-size:18px;color:#EA4335">Some problem occurred, please try again.</span>');
                }
                $('#fupForm').css("opacity","");
                $(".submitBtn").removeAttr("disabled");
            }
        });
    });

    //file type validation
    $("#file").change(function() {
        var file = this.files[0];
        var imagefile = file.type;
        var match= ["image/jpeg","image/png","image/jpg"];
        if(!((imagefile==match[0]) || (imagefile==match[1]) || (imagefile==match[2]))){
            alert('Please select a valid image file (JPEG/JPG/PNG).');
            $("#file").val('');
            return false;
        }
    });
});
</script>

submit.php

<?php
if(!empty($_POST['name']) || !empty($_POST['email']) || !empty($_FILES['file']['name'])){
    $uploadedFile = '';
    if(!empty($_FILES["file"]["type"])){
        $fileName = time().'_'.$_FILES['file']['name'];
        $valid_extensions = array("jpeg", "jpg", "png");
        $temporary = explode(".", $_FILES["file"]["name"]);
        $file_extension = end($temporary);
        if((($_FILES["hard_file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/jpeg")) && in_array($file_extension, $valid_extensions)){
            $sourcePath = $_FILES['file']['tmp_name'];
            $targetPath = "uploads/".$fileName;
            if(move_uploaded_file($sourcePath,$targetPath)){
                $uploadedFile = $fileName;
            }
        }
    }

    $name = $_POST['name'];
    $email = $_POST['email'];

    //include database configuration file
    include_once 'dbConfig.php';

    //insert form data in the database
    $insert = $db->query("INSERT form_data (name,email,file_name) VALUES 
    ('".$name."','".$email."','".$uploadedFile."')");

    echo $insert?'ok':'err';
}

1 个答案:

答案 0 :(得分:1)

错误出在您的PHP中,您尝试检查给定$_FILES['hard_file']['type']的文件类型$_FILES['file']['type']

  if(!empty($_POST['name']) || !empty($_POST['email']) || !empty($_FILES['file']['name'])){
$uploadedFile = '';
if(!empty($_FILES["file"]["type"])){
    $fileName = time().'_'.$_FILES['file']['name'];
    $valid_extensions = array("jpeg", "jpg", "png");
    $temporary = explode(".", $_FILES["file"]["name"]);
    $file_extension = end($temporary);
    if((($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/jpeg")) && in_array($file_extension, $valid_extensions)){
        $sourcePath = $_FILES['file']['tmp_name'];
        $targetPath = "./".$fileName;
        if(move_uploaded_file($sourcePath,$targetPath)){
            $uploadedFile = $fileName;
        }
    }
}