Upload file data via ajax request

2019-09-17 05:17发布

I need to upload files via my form but I don't know how to incorporate a file upload into my form for posting blog entries. I don't know how to perform ajax with JQuery. I don't know how to send the image file/data via the ajax request, any help would be appreciated.

This is what've got atm:

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条回答
乱世女痞
2楼-- · 2019-09-17 05:59

Uploading files with AJAX is not supported using the old XmlHttpRequest object. Possible workarounds include using file upload controls such as Uploadify, Fine Uploader or the jQuery form plugin which supports uploading files. Also modern browsers that support the HTML 5 File API and the XmlHttpRequest2 object would allow you to achieve that natively. Take a look at the following article which illustrates how this could be achieved.

For example let's suppose that you have the following HTML form:

<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>

you could have a script that will perform the upload using 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;
}

You might also take a look at the following article about HTML5 forms.

查看更多
登录 后发表回答