Upload Image file using AJAX and jQuery

|
| By Webner

This functionality is used when we want to store an image and display it on the screen without reloading the whole page.

  1. Create Html file and write down the following code to upload an image.

    html
    The above code will display the screen as following:
    image in jQuery
    Description of the above screen: Once you will choose the file and click the upload button it will display your selected file in blank white space.
    For example, I am selecting an image to preview, and the following is the screenshot after uploading the file without reloading the page.
    file-02

  2. Create a CSS file named custom.css and paste the below code.

    .container{
    margin: 0 auto;
    border: 0px solid black;
    width: 50%;
    height: 250px;
    border-radius: 3px;
    background-color: black;
    text-align: center;
    margin: auto;
    margin-top: 129px;
    }
    /* Preview */
    .preview{
    width: 100px;
    height: 100px;
    border: 1px solid black;
    margin: 0 auto;
    background: white;
    }
    .preview img{
    display: none;
    }
    /* Button */
    .button{
    border: 0px;
    background-color: deepskyblue;
    color: white;
    padding: 5px 15px;
    margin-left: 10px;
    }

  3. Create a PHP file named as imgupload.php

    <?php
    if(isset($_FILES['file']['name'])){ // check for if file exists
    /* Getting file name */
    $filename = $_FILES['file']['name'];
    /* Location */
    $location = "upload/".$filename; // location to upload file
    $imageFileType = pathinfo($location,PATHINFO_EXTENSION);
    $imageFileType = strtolower($imageFileType);
    /* Valid extensions */
    $valid_extensions = array("jpg","jpeg","png");//image with only given extensions are allowed
    $response = 0;
    /* Check file extension */
    if(in_array(strtolower($imageFileType), $valid_extensions)) {
    /* Upload file */
    if(move_uploaded_file($_FILES['file']['tmp_name'],$location)){
    $response = $location;
    }
    }
    echo $response;
    exit;
    }
    echo 0;

Once the upload button will be clicked it will go to the imgupload.php file as we have given this URL to Ajax call on click of upload and with the written code file will be uploaded to the given path in the file imgupload.php file.

Leave a Reply

Your email address will not be published. Required fields are marked *