Ajax文件上传无法在Chrome中运行

时间:2017-02-27 16:38:19

标签: javascript php jquery ajax google-chrome

我在Safari中测试了这个脚本,并且它可以工作,但我在Chrome中尝试过,但它不起作用,并且不打印$status。问题是什么?

HTML文件:

<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<span id="success"></span>
<form id="upload" method="post" enctype="multipart/form-data">
    <input type="text" name="username" id="username">
    <input type="file" name="imagefile" id="imagefile">
    <input type="submit" name="uploadsubmit" id="uploadsubmit">
</form>

<script>

$(document).ready(function(){

    $('#upload').on('submit', function(e) {
        e.preventDefault();

        var username = $('#username').val();
        if (username == '') {
            alert("Empty!");
        } else {
            $.ajax({
                url: "upload.php",
                type: "POST",
                data: new FormData(this),
                contentType: false,
                processData: false,
                success: function(data) {
                    $('#success').html(data);
                    alert("Success!");
                }
            });
        }
    });
});
</script>

PHP文件:

<?php  

$connect = mysqli_connect("localhost", "root", "", "db");
$con=mysqli_connect("localhost","root","","db");
if (mysqli_connect_errno())
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$status = '';

if(isset($_POST['uploadsubmit'])) {

    $username = $_POST["username"];
    if($_FILES['imagefile']['name'] != '') {

        $target = "/images";
        $target = $target . basename($_FILES['imagefile']['name']);
        if (move_uploaded_file($_FILES['imagefile']['tmp_name'], $target)) {

            mysqli_query($con,"SELECT * FROM users");
            mysqli_query($con,"INSERT INTO users (username,images) 
            VALUES ('".$username."','".$target."')");

            mysqli_close($con);

            $status = "Successfull upload with image!";
            $imagefile = pathinfo($target, PATHINFO_EXTENSION);
            $check = getimagesize($target);
            if ($check !== false) {
                echo "This file is image - " . $check["mime"] . ".<br>";
                $uploadOk = 1;
            } else {
                echo "This file is not image!";
                $uploadOk = 0;
            }
        } else {
            $status = "Sorry, we have problem!";
        }
    } else {
        mysqli_query($con,"SELECT * FROM users");
        mysqli_query($con,"INSERT INTO users (username,images) 
        VALUES ('".$username."','no')");

        mysqli_close($con);

        $status = 'Successfull upload without image!';
    }
    echo "Status: {$status}";
}
?>

0 个答案:

没有答案