How to Create Files and Upload File to PHP with jQuery AJAX. File Upload using Ajax with PHP and jQuery. Let's start by creating a form that has a file input and the submit button. below are the code example to help you to upload file using ajax 


Step 1 create file upload form 

Create html form to make choose file button then we will process it via jquery ajax $.ajax


#index.php

<!doctype html>
<html>
    <head lang="en">
        <meta charset="utf-8">
        <title>Ajax File Upload tutorial</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    </head>
    <body>
        <div class="container">
            <div class="row">
                <div class="col-md-8">
                    <h4>
                        Ajax File Uploading
                    </h4>
                    <hr> 
                    <input id="uploadImage" type="file" accept="image/*" name="image" class="uploadimg"/>
                    <div id="err"></div>
                </div>
            </div>
        </div>
        <script>
            $(document).ready(function() {
                $('.uploadimg').on('change', function() {
                    console.log("test");
                    var file_data = $(this).prop('files')[0];
                    var form_data = new FormData();
                    // allow specific image extentions
                    var ext = $(this).val().split('.').pop().toLowerCase();
                    if ($.inArray(ext, ['png', 'jpg', 'jpeg']) == -1) {
                        alert("only jpg and png images allowed");
                        return;
                    }
                    var picsize = (file_data.size);
                    console.log(picsize); /*in byte*/
                    if (picsize > 2097152) /* 2mb*/
                    {
                        alert("Image allowd less than 2 mb")
                        return;
                    }
                    form_data.append('file', file_data);
                    $.ajax({
                        url: 'upload.php', /*point to server-side PHP script */
                        dataType: 'text', /* what to expect back from the PHP script, if anything*/
                        cache: false,
                        contentType: false,
                        processData: false,
                        data: form_data,
                        type: 'post',
                        success: function(res) {
                            console.log(res);
                        }
                    });
                });
            })

        </script>
    </body>
</html>

Step 2 : Sending file from client to searver Via PHP

Create upload.php in root directory then using then check some validation like file size and extension etc and use move_uploaded_file to transfer files from your local computer to server

#upload.php

<?php

$valid_extensions = array('jpeg', 'jpg', 'png');

if (0 < $_FILES['file']['error']) {
    echo 'Error: ' . $_FILES['file']['error'] . '<br>';
} else {

    /* rename the file name */
    $code = md5(mt_rand(10, 100));
    $size = $_FILES['file']['size'];
    $ext = strtolower(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION));

    /* 2 mb 1024*1024 bytes */
    if ($size > 2097152) {
        echo json_encode(array("statusCode" => 400, 'msg' => "Image allowd less than 2 mb"));
    } else if (!in_array($ext, $valid_extensions)) {
        echo json_encode(array("statusCode" => 400, 'msg' => $ext . ' not allowed'));
    } else {

        $result = move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $code . '.' . $ext);
        echo json_encode(array("statusCode" => 200, 'code' => $code));
    }
}
?>

Run the following code to see the result in your browser.

Thanks i hope you will like the tutorial  


Download source code

Are you facing problems in understanding this article? download source code now