通过ajax请求上传文件数据

时间:2013-02-05 07:50:06

标签: javascript ajax jquery file-upload

我需要通过我的表单上传文件,但我不知道如何将文件上传合并到我的表单中以发布博客条目。 我不知道如何使用JQuery执行ajax。 我不知道如何通过ajax请求发送图像文件/数据,我们将不胜感激。

这就是以下内容:

CP.PHP

<?php
    include("../scripts/database_connx.php");
    include("../scripts/functions.php");
    start_secure_session();
    if(logged_in($sqli_con) === false) {
        header("Location: ../index.php");
        exit();
    }
    $cp = true;
?>
<!DOCTYPE HTML>
<html>
    <head>
        <meta charset="UTF-8" />
        <title>TridantDesigns | Admin</title>
        <link rel="stylesheet" type="text/css" href="../style/reset.css" />
        <link rel="stylesheet" type="text/css" href="../style/main.css" />
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
        <script>
            $(document).ready(function() {
                setInterval(function() {
                    if(window.XMLHttpRequest) {
                        get_entries = new XMLHttpRequest();
                    } else {
                        get_entries = new ActiveXObject("Microsoft.XMLHTTP");
                    }

                    get_entries.onreadystatechange = function() {
                        if(get_entries.readyState == 4 && get_entries.status == 200) {
                            document.getElementById("r_e").innerHTML = get_entries.responseText;
                        }
                    }

                    get_entries.open("GET", "get_entries.php", true);
                    get_entries.send();
                }, 50000);
            });
        </script>
    </head>
    <body>
        <?php include("../scripts/includes/header.inc.php"); ?>
        <div id="site_content">
            <div id="new_entry">
                <form>
                    <h1>Add A New Blog Entry</h1>
                    <input type="text" name="entry_title" maxlength="40" placeholder="Entry Title(40 Char)" /><br />
                    <textarea name="entry_contents" placeholder="Entry Content" /></textarea><br />
                    <label for="image">Choose Image File:</label>
                    &nbsp;<input type="file" name="image" /><br />
                    <input type="button" value="Post Entry" onclick="post_entry(this.form, this.form.entry_title, this.form.entry_contents, this.form.image);" />
                </form>
                <div id="post_error">

                </div>
            </div>

            <div id="remove_entry">
                <h1>Remove Entries(Click to remove)</h1>
                <div id="r_e">
                    <?php
                        get_entries($sqli_con);
                    ?>
                </div>
            </div>
        </div>

        <script>
            function post_entry(form, title, contents, image) {
                document.getElementById("post_error").style.display = "block";
                if(title.value.length < 1) {
                    document.getElementById("post_error").innerHTML = "Please enter an entry title!";
                    return;
                }
                if(title.value.length > 40) {
                    document.getElementById("post_error").innerHTML = "Title can not be longer than 40 characters!";
                    return;
                }
                if(contents.value.length < 1) {
                    document.getElementById("post_error").innerHTML = "Please enter some content!";
                    return;
                }

                if(window.XMLHttpRequest) {
                    post_entry_ = new XMLHttpRequest();
                } else {
                    post_entry_ = new ActiveXObject("Microsoft.XMLHTTP");
                }

                post_entry_.onreadystatechange = function() {
                    if(post_entry_.readyState == 4 && post_entry_.status == 200) {
                        document.getElementById("post_error").innerHTML = post_entry_.responseText;
                        if(post_entry_.responseText == "<response>Entry Added</response>") {
                            //get_entries();
                        }
                    }
                }

                post_entry_.open("POST", "add_entry.php", true);
                post_entry_.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
                post_entry_.send("title="+title.value+"&contents="+contents.value+"&image="+image.value);

            }

            function remove_entry() {

            }
        </script>
        <?php include("../scripts/includes/footer.inc.php"); ?>
    </body>
</html>

Add_Entry.PHP

<?php
    include("../scripts/database_connx.php");
    include("../scripts/functions.php");
    start_secure_session();

    if(logged_in($sqli_con) === false) {
        header("Location: ../index.php");
        exit();
    }

    $title = mysqli_escape_string($sqli_con, strip_tags($_POST['title']));
    $contents = mysqli_escape_string($sqli_con, strip_tags($_POST['contents']));
    $image = mysqli_escape_string($sqli_con, strip_tags($_POST['image']));
    $poster = mysqli_escape_string($sqli_con, strip_tags($_SESSION['tridantblog_username']));

    echo var_dump($image);

    if($image == "") {
        if($stmt = $sqli_con->prepare("INSERT INTO entries (title, contents, poster) VALUES (?, ?, ?)")) {
            $stmt->bind_param("sss", $title, $contents, $poster);
            $stmt->execute();
            $stmt->store_result();
            $stmt->fetch();
            if($stmt->rows_affected > 0) {
                $stmt->close();
                echo "<response>Added to database!</response>";
            } else {
                $stmt->close();
                echo "<response>Could not add entry to the database!</response>";
            }
        }
    } else {

        #Check and upload images here!

        if($stmt = $sqli_con->prepare("INSERT INTO entries (title, contents, image, poster) VALUES (?, ?, ?, ?)")) {
            $stmt->bind_param("sss", $title, $contents, $poster);
            $stmt->execute();
            $stmt->store_result();
            if($stmt->rows_affected > 0) {
                $stmt->close();
                echo "<response>Added to database!</response>";
            } else {
                $stmt->close();
                echo "<response>Could not add entry to the database!</response>";
            }
        }
    }
?>

1 个答案:

答案 0 :(得分:2)

使用旧的XmlHttpRequest对象不支持使用AJAX上传文件。可能的解决方法包括使用文件上传控件,例如UploadifyFine Uploader或支持上传文件的jQuery form plugin。此外,支持HTML 5 File API和XmlHttpRequest2对象的现代浏览器将允许您本机实现。看看following article,它说明了如何实现这一目标。

例如,假设您有以下HTML表单:

<form action="upload.cgi" method="post" enctype="multipart/form-data" onsubmit="return upload(this);">
    <input type="file" name="file" />
    <button type="submit">Upload file to the server</button>
</form>

您可以使用AJAX执行上传的脚本:

function upload(formElement) {
    var xhr = new XMLHttpRequest();
    xhr.open(formElement.method, formElement.action);
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            // Handle response.
            alert(xhr.responseText); // handle response.
        }
    };
    xhr.send(new FormData(formElement));
    return false;
}

您还可以查看有关HTML5表单的following article