Sunday 9 September 2018

Upload Image in Laravel using Ajax



Hi, In this tutorial you can find how to upload image or file on folder by using Ajax in Laravel Framework. In one of our post on Laravel framework, in which we have describe how to upload image file in Laravel with validation with complete source code. If you have seen that post then you can simple way to upload file in Laravel but now if you want to learn file upload with Ajax in Laravel, then from this post you can simple way to learn step by step file upload in Laravel using Ajax.

There are many benifits of using Ajax in Laravel like it will reduce traffic between client and server. Ajax will increase the performance and speed of your Laravel web application. By using Ajax we can send and receive data in lightweight json format. So, there are other more benifits of using Ajax in Laravel application. So, If we have you use Ajax in file upload in Laravel then Ajax will increase our file upload speed and it will upload file without refresh of web page and it will reduce load on our web site.

Uploading File or Image is a basic feature of any web application and it is required in most of the web application. If we have use Laravel framework for our web application development then in web application we want to store profile image, product image etc. So, Laravel provide file upload library and by using it we can store image or file on server. Laravel provide image or file upload with validation like file type image or other type of file, file extension, maximum file size etc. So, We have use Ajax form data object in Laravel for upload file then it will become good of our UI also. So, In this post we will learn you how to upload image using Ajax jQuery in Laravel. Here we have use FormData() object in Ajax for upload image in Laravel with display of success and error message on web page.




Install Laravel Application


Here we have store from scratch, so first we want to Install Laravel application, For this we have to run following command in your terminal or command prompt.


composer create-project --prefer-dist laravel/laravel student_crud






Create Controller


This is next step in which we want to create controller in our Laravel application for handle http request for upload file using Ajax. For this we have to write following command in our terminal or command prompt.


php artisan make:controller AjaxUploadController


The above command will make controller file in app/Http/Controllers/AjaxUploadController.php. In this file we have make to method.

  • index() - This is root method of this class and it will load ajax_upload.blade.php file in browser.
  • action() - This method has receive ajax request for upload file on server. In this method first we have validate file using Validator Laravel library and after upload file under images folder. After done upload it will return response in JSON format.

app/Http/Controllers/AjaxUploadController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Validator;

class AjaxUploadController extends Controller
{
    function index()
    {
     return view('ajax_upload');
    }

    function action(Request $request)
    {
     $validation = Validator::make($request->all(), [
      'select_file' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048'
     ]);
     if($validation->passes())
     {
      $image = $request->file('select_file');
      $new_name = rand() . '.' . $image->getClientOriginalExtension();
      $image->move(public_path('images'), $new_name);
      return response()->json([
       'message'   => 'Image Upload Successfully',
       'uploaded_image' => '<img src="/images/'.$new_name.'" class="img-thumbnail" width="300" />',
       'class_name'  => 'alert-success'
      ]);
     }
     else
     {
      return response()->json([
       'message'   => $validation->errors()->all(),
       'uploaded_image' => '',
       'class_name'  => 'alert-danger'
      ]);
     }
    }
}
?>


Create View


Once you have make controller then you have to make view file and this file has been load by controller. So, Here we have make view file resources/views/ajax_upload.blade.php. This is html output file and in this file we have use jQuery and Bootstrap library. In this file we have also write Ajax code for send upload file request to Controllers. Here we have use FormData() object for send file to Controller.

resources/views/ajax_upload.blade.php

<!DOCTYPE html>
<html>
 <head>
  <title>Upload Image in Laravel using Ajax</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
 </head>
 <body>
  <br />
  <div class="container">
   <h3 align="center">Upload Image in Laravel using Ajax</h3>
   <br />
   <div class="alert" id="message" style="display: none"></div>
   <form method="post" id="upload_form" enctype="multipart/form-data">
    {{ csrf_field() }}
    <div class="form-group">
     <table class="table">
      <tr>
       <td width="40%" align="right"><label>Select File for Upload</label></td>
       <td width="30"><input type="file" name="select_file" id="select_file" /></td>
       <td width="30%" align="left"><input type="submit" name="upload" id="upload" class="btn btn-primary" value="Upload"></td>
      </tr>
      <tr>
       <td width="40%" align="right"></td>
       <td width="30"><span class="text-muted">jpg, png, gif</span></td>
       <td width="30%" align="left"></td>
      </tr>
     </table>
    </div>
   </form>
   <br />
   <span id="uploaded_image"></span>
  </div>
 </body>
</html>

<script>
$(document).ready(function(){

 $('#upload_form').on('submit', function(event){
  event.preventDefault();
  $.ajax({
   url:"{{ route('ajaxupload.action') }}",
   method:"POST",
   data:new FormData(this),
   dataType:'JSON',
   contentType: false,
   cache: false,
   processData: false,
   success:function(data)
   {
    $('#message').css('display', 'block');
    $('#message').html(data.message);
    $('#message').addClass(data.class_name);
    $('#uploaded_image').html(data.uploaded_image);
   }
  })
 });

});
</script>


Set Route


Lastly we want to set route of index() and action() method of AjaxUploadController.php Controller. For this we have go to routes/web.php and here we have to set route for both method.


<?php



Route::get('/ajax_upload', 'AjaxUploadController@index');

Route::post('/ajax_upload/action', 'AjaxUploadController@action')->name('ajaxupload.action');


Once you have done all above step the you have to go to terminal or command prompt and write following command. This command will run you laravel application.


php artisan serve


16 comments:

  1. Every good.
    But how to change the image and del old image, thks

    ReplyDelete
    Replies
    1. Hi Michael Ong,

      This is code for delete previous image and upload new image

      if ($request->file('school_extra_logo')) {
      $image = $request->file('school_extra_logo');
      $newName = 'school_extra_logo.' . $image->getClientOriginalExtension();
      $fullPathName = 'uploads/school_logo' . $newName;
      $image->move(public_path('uploads/school_logo'), $newName);
      Storage::delete($fullPathName);
      $data['extra_logo'] = $fullPathName;
      }

      Delete
  2. its not working on my system....
    No response

    ReplyDelete
  3. Muito bom, me ajudou aqui hehe

    ReplyDelete
  4. this is good its working but how can we upload image from img tag not from input box

    ReplyDelete
  5. Da real MVP! It's finaly working. I struggled with the file upload and the new FormData(this) saved me

    ReplyDelete