无法使用ajax上传照片

时间:2017-03-06 09:04:11

标签: php jquery ajax

我正在尝试制作一个上传表格,上传带有ajax的照片,但我目前遇到的问题是,它并没有真正理解它。这是一个代码,所以你有任何想法,为什么它不起作用?

<form id="commentForm" enctype="multipart/form-data">
										<input type="file" name="fileToUpload">
    <button type="submit" name="commentSubmit" id="commentButton" class="btn green"><i class="fa fa-paper-plane"></i> </button>
</form>
<div id="output">GGG</div>
<script type="text/javascript">
    $('#commentForm').on('submit',(function(e) {

        e.preventDefault();

        $.ajax({
            type: 'post',
            url: 'test2.php',
            cache: false,
            contentType: false,
            processData: false,
            data: $('#commentForm').serialize(),
            success: function (html) {
                $('#output').html(html);

            }
        })
    }));
</script>

这里是“test2.php”

<?php


$day_hour = date("H");
$day_min = date("i");
$day_sec = date("s");


if (isset($_FILES["fileToUpload"]["tmp_name"])) {
error_reporting(0);
$target_dir = "upload/";
$target_file = $target_dir . $photo_name_codi . "TSG" . $day_hour . $day_min . $day_sec . "_" . rand(100, 999) . ".jpg";
$uploadOk = 1;
$imageFileType = pathinfo($target_file, PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if (isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if ($check !== false) {
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif"
) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file " . $target_file . " has been uploaded. " . $imageFileType;
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}

1 个答案:

答案 0 :(得分:0)

试试这个:

HTML:

<input id="pic" type="file" name="pic" />
<button id="upload">Upload</button>

Jquery的:

$('#upload').on('click', function() {
        var file_data = $('#pic').prop('files')[0];
        var form_data = new FormData();
        form_data.append('file', file_data);

        $.ajax({
                url         : 'upload.php',     // point to server-side PHP script 
                dataType    : 'text',           // what to expect back from the PHP script, if anything
                cache       : false,
                contentType : false,
                processData : false,
                data        : form_data,                         
                type        : 'post',
                success     : function(output){
                    alert(output);              // display response from the PHP script, if any
                }
         });
         $('#pic').val('');                     /* Clear the file container */
    });

腓:

<?php
    if ( $_FILES['file']['error'] > 0 ){
        echo 'Error: ' . $_FILES['file']['error'] . '<br>';
    }
    else {
        if(move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']))
        {
            echo "File Uploaded Successfully";
        }
    }

?>