使用AJAX传递图像文件是不成功的

时间:2015-12-23 06:56:32

标签: javascript php html ajax

嘿伙计们我遇到了一个错误,我在上传图片文件时无法通过AJAX传递图像文件。这是我的代码

AJAX

    var file = $("#thumbnail").get(0).files[0];
alert(file.name+" | "+file.size+" | "+file.type);
var formdata = new FormData();
formdata.append("file", file);

alert (formdata);

    $.ajax({
        url: "php/post-check.php",
        type: "POST",
        data: {
            title: title,
            thumbnail: formdata
        },
        success: function (data) {
            $("div#postresult").removeClass("alert alert-danger");
            $("div#postresult").html(data);
        }
    });

PHP

<?php 
        $target_dir = "../thumbnail-pictures/";
        $target_file = $target_dir . basename($_FILES["thumbnail"]["name"]);
        $uploadOk = 1;
        $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

        if (file_exists($target_file)) {
            echo "Sorry, thumbnail file already exists. <br>";
            $uploadOk = 0;
        }

        if ($_FILES["thumbnail"]["size"] > 1000000) {
            echo "Sorry, your file is too large.";
            $uploadOk = 0;
        }

        if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg") {
            echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
            $uploadOk = 0;
        }

        if ($uploadOk == 0) {
            echo "Sorry, your file was not uploaded, ";

        } else {
            if (move_uploaded_file($_FILES["thumbnail"]["tmp_name"], $target_file)) {

            } else {
                echo "Sorry, there was an error uploading your file.";
            }
        }
        ?>

HTML

<form action="" method="post" enctype="multipart/form-data" id="newpost">
                <div class="col-lg-12">
                        <div class="form-group">
                            <label>Title</label>
                            <input class="form-control" name="title" id="title" required>

                        </div>

                        <div class="form-group">
                            <label>Video Thumbnail **Only JPEG & PNG is accepted**</label>
                            <input type="file" name="thumbnail" id="thumbnail" accept="image/png, image/gif, image/jpeg" >
                        </div>

PHP代码本身工作正常,所以我认为问题在于AJAX部分,但我不确定如何解决这个问题。感谢任何帮助!

3 个答案:

答案 0 :(得分:0)

问题应该在参数 processData 上,请添加参数processData: false, 到您的ajax请求并尝试在php上获取您的图像。

            $.ajax({
                url: formURL,
                type: form.attr('method'),
                dataType: 'json',
                data: formData,//form.serialize(),
                processData: false,  // tell jQuery not to process the data
                contentType: false,   // tell jQuery not to set contentType
                beforeSend: function(){},
                success: function(data, textStatus, jqXHR) {},
                error: function(jqXHR, textStatus, errorThrown) 
               {
                  alert(jqXHR+ textStatus+ errorThrown);
                },
              complete: function(){}
                });

希望help.good运气

答案 1 :(得分:0)

将输入正确地放在一个表单中,然后使用FormData()将表单作为一个整体发送。我会建议这样的事情:

<form method="post" enctype="multipart/formdata" id="myForm">
   <input type="text" name="title" />
   <input type="file" name="thumbnail" />
</form>

使用js:

构建和发送数据
var form = document.getElementById('myForm');
var formData = new FormData(form);

alert (formdata);

$.ajax({
    url: "php/post-check.php",
    type: "POST",
    data: formData,
    success: function (data) {
        $("div#postresult").removeClass("alert alert-danger");
        $("div#postresult").html(data);
    }
});

现在你可以像这样在php中获取数据:

$title = $_POST['title'];
$thumb = $_FILES['thumbnail'];
$tmp_file_path = $thumb['tmp_name'];

答案 2 :(得分:-1)

您可以使用ajaxForm()将整个表单发布到异步中,如下所示:

$("#newpost").ajaxForm({
    success: function(data) {
        $("div#postresult").removeClass("alert alert-danger");
        $("div#postresult").html(data);
    },
    error: function(a, textStatus, exception) {

    }
});

AjaxForm不是核心JQuery的一部分,但您可以找到源here和文档here