Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • File upload using ajax

    • 0
    • 1
    • 1
    • 1
    • 0
    • 0
    • 0
    • 0
    • 224
    Comment on it

    File uploading is the basic requirement of web development. Many times we have to upload single or multiple files on our server then we can not upload big files using form submit. We have to use the in-build jquery plugins for the file upload. These plugins will use the flash in file uploading but we want to upload files using sample javascript so let go to do the same. Firstly we have to write the html part like below

    <!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 file</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="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
      <script src="upload.js"></script>
    </body>
    </html>
    

    We have implemented a simple html form with file upload option. Now we are going to write down the javascript code. Please have a look.

    (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);
    }());
    

    In above script, we got all the files selected and append these files to the formdata object. We have create object of XMLHttpRequest to make the communication with the server. To open the new connection we have to use the open function.
    It takes three different parameters like method, url and asynchronous request or not with Boolean parameter. In the end we check the status and displayed the message accordingly. You can get the files data on file upload-ajax.php and move the files in selected folder.

    <?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>";
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: