有问题通过jQuery Ajax上传文件(图像)到服务器

时间:2015-09-15 21:54:14

标签: php jquery ajax

您能否请看一下这些片段,让我知道将图片上传到根目录中的img文件夹时出错了什么?

我有简单的输入模板,如

Bug Title:<br>
<input type="text" name="bugTitle">
Bug Description: 
<textarea name="bugDescriotion"></textarea>
Bug Image:<br>
<input type="file" id="input" name="bug-img">

和jquery Ajax请求,如

 $("#submit-bug").on("click", function(e) {
     var mdata = new FormData();
     mdata.append('bug_title', $('input[name=bugTitle]').val());
     mdata.append('bug_description', $('input[name=bugDescriotion]').val());
     mdata.append('bug_img', $('input[name=bug-img]')[0].files[0]);

     e.preventDefault();
     var request = $.ajax({
         type: "POST",
         url: "loadBugs.php",
         data: mdata,
         cache: false,

         processData: false,
         beforeSend: function() {
             console.log(mdata);
         }
     });

     request.done(function(data) {
         console.log(data);
     });

     request.fail(function(jqXHR, textStatus) {
         console.log("Request failed: " + textStatus);
     });

 });

最终是一个名为 loadBugs.php

的php filr
<?php
header('Content-type: application/json');
$validextensions = array("jpeg","jpg", "png");
$temporary       = explode(".", $_FILES["bug_img"]["name"]);
$file_extension  = end($temporary);
if ((($_FILES["bug_img"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/jpeg")) && ($_FILES["file"]["size"] < 100000) //Approx. 100kb files can be uploaded.
    && in_array($file_extension, $validextensions)) {
    if ($_FILES["file"]["error"] > 0) {
        echo "Return Code: " . $_FILES["file"]["error"] . "<br/><br/>";
    } else {
        if (file_exists("img/" . $_FILES["file"]["name"])) {
            echo $_FILES["file"]["name"] . " <span id='invalid'><b>already exists.</b></span> ";
        } else {
            $sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
            $targetPath = "img/" . $_FILES['file']['name']; // Target path where file is to be stored
            move_uploaded_file($sourcePath, $targetPath); // Moving Uploaded file
            echo "<span id='success'>Image Uploaded Successfully...!!</span><br/>";
        }
    }
} else {
    echo "<span id='invalid'>Invalid file Size or Type<span>";
}

?>

1 个答案:

答案 0 :(得分:1)

<?php   $validextensions = array("jpeg","jpg", "png");
    $type = ["image/png","image/jpg","image/jpeg"];
    $file_extension  = pathinfo($_FILES["bug_img"]["name"], PATHINFO_EXTENSION);
        if(!in_array($_FILES["bug_img"]["type"],$type)){
            die("Wrong File type");
        }
        if ($_FILES["file"]["size"] < 100000) {
            die("Size not Allowed");}
        if(!in_array($file_extension, $validextensions)) {
            die("FILE EXTENSION NOT ALLOWED");
        }
        if ($_FILES["file"]["error"] > 0) {
                die( "Return Code: " . $_FILES["file"]["error"] . "<br/><br/>");
        }
        if (file_exists("img/" . $_FILES["file"]["name"])) {
            die($_FILES["file"]["name"] . " <span id='invalid'><b>already exists.</b></span> ");
        }
            $sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
            $targetPath = "img/" . $_FILES['file']['name']; // Target path where file is to be stored
        if(move_uploaded_file($sourcePath, $targetPath)){
            echo "<span id='success'>Image Uploaded Successfully...!!</span><br/>";
        }
                    ?>

首先是您的内容类型

header('Content-type: application/json');

错了,你没有回json。

其次,您应该检查开发工具以查看您要发送和接收的内容。 (我没试过,但它应该工作) 第三,应使用PathINFO检查文件扩展名而不是爆炸。