Friday 27 January 2017

Jquery,Ajax file upload in PHP

There are plenty of free jquery,ajax file upload plugins are available to download from google.
But if you want to learn your own way to do this , we have written tutorials for image uploading using Jquery,Ajax in PHP.
In this tutorial we will able to upload images without page reloading .

jquery, ajax file upload in php
First we have to create a HTML file to display form for uplaoding image .Find below it’s code
<form>      
    <div id="upload">
        <p>Select file to upload</p>
    </div>
    <input type="file" name="fileInput" id="fileInput" />
</form>
We also require some css for stylizing the HTML form upload page. Find below css code
#upload{
    border: 3px dashed #0087F7;
    border-radius: 5px;
    background: #F3F4F5;
    cursor: pointer;
}

#upload{
    min-height: 150px;
    padding: 54px 54px;
    box-sizing: border-box;
}
#upload p{
    text-align: center;
    margin: 2em 0;
    font-size: 16px;
    font-weight: bold;
}
#fileInput{
    display: none;
} 
Now include jquery file to your document . You may either call using any CDN or download jquery and put inside your folder .
We are using CDN as shown below
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
Now put below js code .It will handle user browsed file then send it to upload.php to upload in server using PHP script . This file also limit user to upload maximum 1 MB size of image, Yo can change as per your requirements .
$(function(){
    //file input field trigger when the drop box is clicked
    $("#upload").click(function(){
        $("#fileInput").click();
    });
    
    //prevent browsers from opening the file when its dragged and dropped
    $(document).on('drop dragover', function (e) {
        e.preventDefault();
    });

    //call a function to handle file upload on select file
    $('input[type=file]').on('change', fileUpload);
});

function fileUpload(event){
    //notify user about the file upload status
    $("#upload").html(event.target.value+" uploading...");
    
    //get selected file
    files = event.target.files;
    
    //form data check the above bullet for what it is  
    var data = new FormData();                                   

    //file data is presented as an array
    for (var i = 0; i < files.length; i++) {
        var file = files[i];
        if(!file.type.match('image.*')) {              
            //check file type
            $("#upload").html("Please choose an images file.");
        }else if(file.size > 1048576){
            //check file size (in bytes)
            $("#upload").html("Sorry, your file is too large (>1 MB)");
        }else{
            //append the uploadable file to FormData object
            data.append('file', file, file.name);
            
            //create a new XMLHttpRequest
            var xhr = new XMLHttpRequest();     
            
            //post file data for upload
            xhr.open('POST', 'upload.php', true);  
            xhr.send(data);
            xhr.onload = function () {
                //get response and show the uploading status
                var response = JSON.parse(xhr.responseText);
                if(xhr.status === 200 && response.status == 'ok'){
                    $("#upload").html("File has been uploaded successfully. Click to upload another.");
                }else if(response.status == 'type_err'){
                    $("#upload").html("Please choose an images file. Click to upload another.");
                }else{
                    $("#upload").html("Some problem occured, please try again.");
                }
            };
        }
    }
}
Finally ,we need a php file i.e upload.php .This file first check allowed image extension then it upload to server . Below file also return response in JSON format. We can use this in html page to show any success message .
<?php
if(isset($_POST)){
    //generate unique file name
    $fileName = time().'_'.basename($_FILES["file"]["name"]);
    
    //file upload path
    $targetDir = "uploads/";
    $targetFilePath = $targetDir . $fileName;
    
    //allow certain file formats
    $fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
    $allowTypes = array('jpg','png','jpeg','gif');
    
    if(in_array($fileType, $allowTypes)){
        //upload file to server
        if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){
            //insert file data into the database if needed
            //........
            $response['status'] = 'ok';
        }else{
            $response['status'] = 'err';
        }
    }else{
        $response['status'] = 'type_err';
    }
    
    //render response data in JSON format
    echo json_encode($response);
}

No comments:

Post a Comment