File Upload Using Ajax

Using Basic PHP and JQuery:

There are three main components to our task.
  • The multiple attribute on the file input element.
  • The FileReader object from the new File API.
  • The FormData object from XMLHttpRequest2.
We use the multiple attribute to allow the user to select multiple files for upload (multiple file upload will work normally even if FormData isn’t available). As you’ll see, FileReader allows us to show the user thumbnails of the files they’re uploading (we’ll be expecting images).



HTML Page:

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8" />

    <title>HTML5 File API</title>

    <link rel="stylesheet" href="style.css" />

</head>

<body>

    <div id="main">

        <h1>Upload Your Images</h1>

        <form method="post" enctype="multipart/form-data"  action="upload.php">

            <input type="file" name="images" id="images" multiple />

            <button type="submit" id="btn">Upload Files!</button>

        </form>

        <div id="response"></div>

        <ul id="image-list">

        </ul>

    </div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>

    <script src="upload.js"></script>

</body>

</html>

CSS:(style.css)
body {
    font: 14px/1.5 helvetica-neue, helvetica, arial, san-serif;
    padding:10px;
}
h1 {
    margin-top:0;
}
#main {
    width: 300px;
    margin:auto;
    background: #ececec;
    padding: 20px;
    border: 1px solid #ccc;
}
#image-list {
    list-style:none;
    margin:0;
    padding:0;
}
#image-list li {
    background: #fff;
    border: 1px solid #ccc;
    text-align:center;
    padding:20px;
    margin-bottom:19px;
}
#image-list li img {
    width: 258px;
    vertical-align: middle;
    border:1px solid #474747;
}


PHP File:(upload.php)
<?php
foreach ($_FILES["images"]["error"] as $key => $error) {
    if ($error == UPLOAD_ERR_OK) {
        $name = $_FILES["images"]["name"][$key];
        move_uploaded_file( $_FILES["images"]["tmp_name"][$key], "uploads/" . $_FILES['images']['name'][$key]);
    }
}
echo "<h2>Successfully Uploaded Images</h2>";
?>

Javascript File:
(function () {
    var input = document.getElementById("images"),
        formdata = false;

    function showUploadedItem (source) {
          var list = document.getElementById("image-list"),
              li   = document.createElement("li"),
              img  = document.createElement("img");
          img.src = source;
          li.appendChild(img);
        list.appendChild(li);
    }  

    if (window.FormData) {
          formdata = new FormData();
          document.getElementById("btn").style.display = "none";
    }
   
     input.addEventListener("change", function (evt) {
         document.getElementById("response").innerHTML = "Uploading . . ."
         var i = 0, len = this.files.length, img, reader, file;
   
        for ( ; i < len; i++ ) {
            file = this.files[i];
   
            if (!!file.type.match(/image.*/)) {
                if ( window.FileReader ) {
                    reader = new FileReader();
                    reader.onloadend = function (e) {
                        showUploadedItem(e.target.result, file.fileName);
                    };
                    reader.readAsDataURL(file);
                }
                if (formdata) {
                    formdata.append("images[]", file);
                }
            }   
        }
   
        if (formdata) {
            $.ajax({
                url: "upload.php",
                type: "POST",
                data: formdata,
                processData: false,
                contentType: false,
                success: function (res) {
                    document.getElementById("response").innerHTML = res;
                }
            });
        }
    }, false);
}());

Download code here
Thats it enjoy the coding!!!