How to upload image or file in Laravel using AJAX

By CodersDrive
29-May-2020
Ajax

In this example we will give you step by step procedure for uploading images or files in Laravel application using AJAX. We also provide you a demo link to show how it works.

Example: Upload images <2MB using AJAX

Step-1

Create a page upload_image.blade.php under /resources/views and save it. In this page add the following code.

            
<div class="container">
<h3 class="text-center">Demo for image uploading using AJAX</h3>
    <label for="front_page"><strong>Select image to upload:</strong></label>
          <div class="custom-file mb-3">
                                    
              <input type="file" accept="image/*" class="custom-file-input" name="front_page" id="front_page">
                                    
                   <label class="custom-file-label" for="customFile1">Upload Image using AJAX</label>
                                        
                    <font color="red"><small><b>   </b></small></font>
                    <div class="col-12 justify-content-center" align="center">
                    <span id="uploaded_coverpage"></span>
                    </div>
                  </div>

            </div>

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

            

                $(document).ready( function() {
                    
                

                    $(document).on('change', '#front_page', function(){
                    
                    var name = document.getElementById("front_page").files[0].name;
                    var form_data = new FormData();
                    var ext = name.split('.').pop().toLowerCase();
                    if(jQuery.inArray(ext, ['png','jpg','jpeg']) == -1) 
                    {
                    alert("Invalid File Format (Only images allowed)");
                    }
                    var oFReader = new FileReader();
                    oFReader.readAsDataURL(document.getElementById("front_page").files[0]);
                    var f = document.getElementById("front_page").files[0];
                    var fsize = f.size||f.fileSize;
                    if(fsize > 2000000)
                    {
                    alert("File Size is very big (Allowed size is Max 2MB)");
                    }
                    else
                    {
                        event.preventDefault();
                        
                    form_data.append("file", document.getElementById('front_page').files[0]);

                    $.ajax({
                        url:"/upload-image",
                        method:"POST",
                        data: form_data,
                        contentType: false,
                        cache: false,
                        processData: false,
                        beforeSend:function(){
                        $('#uploaded_coverpage').html("<label class='text-dark'>Cover Page Uploading...(Fill other fields)</label>");
                        },   
                        
                        success:function(data)
                        {
                        $('#uploaded_coverpage').html(data);
                        },
                        resetForm: true
                    });
                    }
                    });

                    $.ajaxSetup({
                                headers: {
                                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                                }
                                });

                });
            </script>
            
            
            
            

Let's understand what this code does. To upload an image or file we must create an input element as type="file". Adding accept="image/*" will make users to see only image mime type files while selecting files from his machine. Add font color="red" element to display any error message arises when uploading image or file. Under div class="col-12 justify-content-center" element add a span id="uploaded_coverpage" element to display the preview of image uploaded.

Now let's move to the Javascript part where the actual AJAX execution exists. Firstly import the concerned ajax jquery library. Let's jump to main part of script. Create an onchange event on the input element created above. Uploaded file name is mapped to name variable and it's extension is mapped to ext variable. The file extension is now verified with our required extensions placed in array. If the extension is not validated an error is returned to user and the script execution terminates. Now we will map the file size to fsize variable and verify the file size. Here we are restricting file size to 2MB as 2000000. If the file size validation is failed an error message is returned to user and script execution terminates. If the file size is <2MB the $.ajax function is called with url as url:"/upload-image" and method as method="POST". Now the beforeSend:function() is used to display a message to user that the uploading is under process. After the file is successfully uploaded success:function(data) will display the preview of uploaded image to user.

It is important to note that in Laravel for POST or GET methods CSRF token is to be mandatorly passed with elements otherwise a 419 error(page expired) will be thrown by the server. To avoid this under $.ajaxSetup pass 'XCSRF-TOKEN' as headres:.

Add a Route in routes/web.php as below to access this page. We should use get method here then we call a function() which returns the view of page we created above when ever a url /upload-image-using-ajax is accessed.

Route::get('/upload-image-using-ajax', function () { return view('upload_image');});

Step-2

Now add a Route in routes/web.php as below. Here we are creating a route for the url /upload-image for which we created the AJAX request earlier. Now we proceed to next step of creating a Controller and adding corresponding function to it as per route.

Route::post('/upload-image', 'AjaxuploadController@upload');

Step-3

Now we will create a Controller to handle image or file uploading at server end. Type the following command at command prompt to create a controller named AjaxuploadController. This will create the controller at location app/HTTP/Controllers.

php artisan make:controller AjaxuploadController

Open the controller file created above and add the following code.

            
            <?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class AjaxuploadController extends Controller
{
    public function upload()
    {
        if($_FILES["file"]["name"] != '')
            {
                $test = explode('.', $_FILES["file"]["name"]);
                $ext = end($test);
                $name = date_format(now(),'YmdHis').'-'.rand(100, 999) . '.' . $ext;
                if (!file_exists('storage/images')) {
                    mkdir('storage/images', 0777, true);
                }
                $location = 'storage/images/'.$name; 
               
                if($ext == 'jpg' || $ext == 'jpeg' || $ext == 'png')
                {
                    move_uploaded_file($_FILES["file"]["tmp_name"], $location);
                    
                    echo '<img src="'.$location.'" style="height:120px;width:160px;" class="img-thumbnail" /><br><h6>Image successfully uploaded!</h6><input type="text" name="thumbnail" value="'.$location.'" style="width:50%;">';
                    
                } else
                {
                    echo '<h4 class="text-danger">Invalid file type, try again by refreshing.</h4>';
                }
                
                
            }
    }
}
            
            

Now we will see the details about the upload() function here. Firstly it checks for if file exist using if($_FILES["file"]["name"] != '') condition. The function continues only if the file exists. Next it will save the uploaded file name and extension into $test variable as an array. We will save the file extension name into $ext. Here we are changing the uploaded file name with our custom name. For this we are creating a new file name $name using now() and rand() functions to make them unique. now() function is used to get current server date and time. rand(100,999) function will generate a random number between 100 to 999 every time it is called.

Let's check the path/folder on the server where we want to upload this image. If the desired destination is not available we will create it, these action is perfomed by the function if (!file_exists('storage/images')). Here we are uploading the image to storage/images.

Here we will once again check the file extension path using $ext variable which we captured earlier. If this check is passed move_uploaded_file() function will move the file from temp location to our desired location and then using echo() statement we will return the successful message along with the image preview as an HTML code embedded in it. This will be displayed to the user. If the file extension is not matched the server will execute else() statement and returns error message to the user embedded in echo() statement.

Hope by this time you will be able to successfully upload the images using AJAX. To allow upload of document files use proper mime types at accept="image/*" and proper extensions inplace of that of image ones.

Image upload using AJAX Demo

Ajax Laravel Php

Search blog..!

Connect with us