Monday, 24 June 2019

Laravel 5.8 Tutorial - File Upload with Progress Bar using Ajax



If you are looking for Laravel 5.8 web tutorial for learn How to Upload File or Image in Laravel 5.8 with Progress bar for display uploading process, then you have come on right place because you can find complete step by step tutorial for display uploading process in progress bar using Ajax jQuery in Laravel 5.8 framework. Here we have make tutorial on topic like Laravel file upload with Progress bar using Ajax jQuery.

Now in your mind one question is aris why we want to use progress bar while uploading of file. So, the answer is that if you have done file or image uploading in normal way then user can not see uploading process. So it is proper in web development, but if in your application you have to allowed large amount of File or image for uploading then at that time if you have not use progress bar then User of the system did not get idea about image or file has been done uploading or not. So, At that time if you have use progress bar while uploading of file then user can see how many percentage of uploading process of completed and how many percentage is remaining. So, this the main benefits of using progress bar for show uploading process on web page. In this post we will make feature like show progress bar while uploading of file in Laravel 5.8.

Here we have use jQuery Form plugin for submit form data by using Ajax. So for submit form data in Laravel 5.8 application, we have use jQuery form plugin. So, Image or file will be upload without refresh of web page and upload process will be display on web page in progress bar. Below you can find step by step process of how to use jQuery Ajax for upload file with progress bar in Laravel 5.8 framework.

  • Install Laravel 5.8 Framework
  • Create Controllers in Laravel 5.8 application
  • Create Blade File
  • Set Route




Install Laravel 5.8 Framework


For make Laravel 5.8 application, first we want to download and install Laravel 5.8 framework. For this we have go to command prompt, in which we want to first run "composer" command and after this we have to run following command. This command will download Laravel 5.8 framework in your define folder path.


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


Create Controllers in Laravel 5.8 application


In Laravel 5.8 application for handle http request we have to create controller. So for upload file here we have to create one controller for handle http request for upload file. For this we have go to command prompt and write following command.


php artisan make:controller FileUploadController


This command will make FileUploadController.php file in app/Http/Controllers folder. In this folder we have create two method.

index() - This method has load the file_upload.blade.php file in browser for select file from local computer.

upload() - This method has received request for upload file. This method has received ajax request for upload file. In this method first it has validate form data before upload. If form data has not proper then it has send error to Ajax request in JSON format. But suppose there is no any form data validation found then it will process for upload file and send success message to Ajax request in json format.

app/Http/Controllers/FileUploadController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Validator;

class FileUploadController extends Controller
{
    function index()
    {
     return view('file_upload');
    }

    function upload(Request $request)
    {
     $rules = array(
      'file'  => 'required|image|max:2048'
     );

     $error = Validator::make($request->all(), $rules);

     if($error->fails())
     {
      return response()->json(['errors' => $error->errors()->all()]);
     }

     $image = $request->file('file');

     $new_name = rand() . '.' . $image->getClientOriginalExtension();
     $image->move(public_path('images'), $new_name);

     $output = array(
         'success' => 'Image uploaded successfully',
         'image'  => '<img src="/images/'.$new_name.'" class="img-thumbnail" />'
        );

        return response()->json($output);
    }
}

?>


Create Blade File


Laravel 5.8 has been use blade engine for display output in browser. So, we have to create view file under resources/views. In this folder we have create file_upload.blade.php file. In this file we have use jQuery library, Bootstrap library for display progress bar and jQuery form library for submit form data without refresh of web page. Here we have make form for select file from local computer. Under this file we have write jQuery code for display upload process in progress bar. After successfuly upload of image, it will be display on web page.

resources/views/file_upload.blade.php

<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Laravel 5.8 - File Upload with Progressbar using Ajax jQuery</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.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.6/js/bootstrap.min.js"></script>
        <script src="http://malsup.github.com/jquery.form.js"></script>
 </head>
 <body>
  <div class="container">    
     <br />
     <h3 align="center">Laravel 5.8 - File Upload with Progressbar using Ajax jQuery</h3>
     <br />
     <div class="panel panel-default">
                <div class="panel-heading">
                    <h3 class="panel-title">File Upload with Progressbar using Ajax jQuery</h3>
                </div>
                <div class="panel-body">
                    <br />
                    <form method="post" action="{{ route('upload') }}" enctype="multipart/form-data">
                      @csrf
                      <div class="row">
                            <div class="col-md-3" align="right"><h4>Select Image</h4></div>
                            <div class="col-md-6">
                              <input type="file" name="file" id="file" />
                            </div>
                            <div class="col-md-3">
                              <input type="submit" name="upload" value="Upload" class="btn btn-success" />
                            </div>
                        </div>
                    </form>
                    <br />
                    <div class="progress">
                      <div class="progress-bar" role="progressbar" aria-valuenow=""
                      aria-valuemin="0" aria-valuemax="100" style="width: 0%">
                        0%
                      </div>
                    </div>
                    <br />
                    <div id="success">

                    </div>
                    <br />
                </div>
            </div>
  </div>
 </body>
</html>

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

    $('form').ajaxForm({
      beforeSend:function(){
        $('#success').empty();
      },
      uploadProgress:function(event, position, total, percentComplete)
      {
        $('.progress-bar').text(percentComplete + '%');
        $('.progress-bar').css('width', percentComplete + '%');
      },
      success:function(data)
      {
        if(data.errors)
        {
          $('.progress-bar').text('0%');
          $('.progress-bar').css('width', '0%');
          $('#success').html('<span class="text-danger"><b>'+data.errors+'</b></span>');
        }
        if(data.success)
        {
          $('.progress-bar').text('Uploaded');
          $('.progress-bar').css('width', '100%');
          $('#success').html('<span class="text-success"><b>'+data.success+'</b></span><br /><br />');
          $('#success').append(data.image);
        }
      }
    });

});
</script>


Set Route


In Laravel 5.8 application, we have to set the route of controller method. For this we have to go to routes/web.php file and in this file we have to define route.

routes/web.php

<?php

Route::get('file-upload', 'FileUploadController@index');

Route::post('file-upload/upload', 'FileUploadController@upload')->name('upload');

?>


Lastly we have to run Laravel 5.8 application on file upload with progress bar. For this we have to command prompt and write following command.


php artisan serve


This command will run Laravel 5.8 application and for test above code you have to write following link in your browser tab.


http://127.0.0.1:8000/file-upload


For test the above code functionality, you have to hit following url in your browser then you can test Laravel 5.8 file upload with progress bar functionality is working or not.

3 comments:

  1. sometimes browser sends this to console on page load:

    Uncaught TypeError: $ is not a function
    at upload_progress_bar.js:69
    at upload_progress_bar.js:21
    at upload_progress_bar.js:25

    then it's not working

    ReplyDelete