Saturday, November 16, 2024
Google search engine
HomeLanguagesMultiple File Upload using Ajax in Laravel 8

Multiple File Upload using Ajax in Laravel 8

Laravel 8 multiple file upload using jQuery ajax example; In this tutorial, you will learn from scratch on how to implement multiple file upload in laravel 8 app using jQuery ajax.

This multiple file upload using ajax in laravel tutorial will create ajax file upload form and write jQuery and code to upload multiple files into database and folder.

You can follow this tutorial and make simple upload multiple files like pdf, txt, xlsx, zip using jQuery ajax in laravel 8 app.

Laravel 8 Multiple File Upload Ajax Tutorial

Use the following steps to upload multiple file using ajax in laravel 8 applications:

  • Step 1 – Install Laravel 8 Application
  • Step 2 – Database Configuration
  • Step 3 – Build File Model & Migration
  • Step 4 – Create Ajax Multiple File Upload Routes
  • Step 5 – Make Controller using Artisan Command
  • Step 6 – Create an Ajax Form to Upload Multiple File
  • Step 7 – Ajax Code to Upload Multiple File
  • Step 8 – Start Development Server

Step 1 – Install Laravel 8 Application

In step 1, open your terminal and navigate to your local web server directory using the following command:

//for windows user
cd xampp/htdocs

//for ubuntu user
cd var/www/html

Then install laravel 8 latest application using the following command:

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

Step 2 – Database Configuration

In step 2, open your downloaded laravel 8 app into any text editor. Then find .env file and configure database detail like following:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db name
DB_USERNAME=db user name
DB_PASSWORD=db password

Step 3 – Build File Model & Migration

In this step, use the below given command to create phtoto migration and model file.

First of all, navigate to project by using the following command:

cd / blog

Then create model and migration file by using the following command:

php artisan make:model File -m

The above command will create two files into your laravel 8 multiple File upload with validation tutorial app, which is located inside the following locations:

  • blog/app/Models/File.php
  • blog/database/migrations/create_files_table.php

So, find create_photos_table.php file inside blog/database/migrations/ directory. Then open this file and add the following code into function up() on this file:

    public function up()
    {
        Schema::create('files', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('path');
            $table->timestamps();
        });
    }

Now, open again your terminal and type the following command on cmd to create tables into your selected database:

php artisan migrate

Step 4 – Create Ajax Multiple File Upload Routes

In this step, open your web.php file, so navigate inside routes directory. Then update the following routes into the web.php file:

use App\Http\Controllers\MultiFileUploadAjaxController;

Route::get('multi-file-ajax-upload', [MultiFileUploadAjaxController::class, 'index']);

Route::post('store-multi-file-ajax', [MultiFileUploadAjaxController::class, 'storeMultiFile']);

Step 5 – Make Controller using Artisan Command

In this step, use the below given php artisan command to create controller:

php artisan make:controller AjaxUploadMultipleImageController

The above command will create AjaxUploadMultipleImageController.php file, which is located inside blog/app/Http/Controllers/ directory.

So open UploadImagesController.php file and add the following code into it:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\File;

class MultiFileUploadAjaxController extends Controller
{
    public function index()
    {
        return view('multi-file-ajax-upload');
    }


    public function storeMultiFile(Request $request)
    {
        
       $validatedData = $request->validate([
        'files' => 'required',
        'files.*' => 'mimes:csv,txt,xlx,xls,pdf'
        ]);

        if($request->TotalFiles > 0)
        {
               
           for ($x = 0; $x < $request->TotalFiles; $x++) 
           {

               if ($request->hasFile('files'.$x)) 
                {
                    $file      = $request->file('files'.$x);

                    $path = $file->store('public/files');
                    $name = $file->getClientOriginalName();

                    $insert[$x]['name'] = $name;
                    $insert[$x]['path'] = $path;
                }
           }

            File::insert($insert);

            return response()->json(['success'=>'Ajax Multiple fIle has been uploaded']);

         
        }
        else
        {
           return response()->json(["message" => "Please try again."]);
        }

    }
}

Step 6 – Create an Ajax Form to Upload Multiple File

In step this, Go to resources/views directory. And then create a new blade view file named multi-file-ajax-upload.blade.php inside this directory.

So, open this multi-file-ajax-upload.blade.php file in text editor and update the following code into it:

<!DOCTYPE html>
<html>
<head>
  <title>Laravel 8 Ajax Multiple File Upload - Tutsmake.com</title>

  <meta name="csrf-token" content="{{ csrf_token() }}">

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

   <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

</head>
<body>

<div class="container mt-5">


    <h2 class="text-center">Multiple File Upload Using Ajax In Laravel 8</h2>

    <div class="text-center">
        <form id="multi-file-upload-ajax" method="POST"  action="javascript:void(0)" accept-charset="utf-8" enctype="multipart/form-data">

          @csrf
                  
            <div class="row">

                <div class="col-md-12">
                    <div class="form-group">
                        <input type="file" name="files[]" id="files" placeholder="Choose files" multiple >
                    </div>
                </div>           
 
                <div class="col-md-12">
                    <button type="submit" class="btn btn-primary" id="submit">Submit</button>
                </div>
            </div>     
        </form>

    </div>

</div>  
<script type="text/javascript">
     
$(document).ready(function (e) {
   
   $.ajaxSetup({
       headers: {
           'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
   });
   
  
   $('#multi-file-upload-ajax').submit(function(e) {

     e.preventDefault();
  
      var formData = new FormData(this);

      let TotalFiles = $('#files')[0].files.length; //Total files
      let files = $('#files')[0];
      for (let i = 0; i < TotalFiles; i++) {
          formData.append('files' + i, files.files[i]);
      }
      formData.append('TotalFiles', TotalFiles);
  
     $.ajax({
        type:'POST',
        url: "{{ url('store-multi-file-ajax')}}",
        data: formData,
        cache:false,
        contentType: false,
        processData: false,
        dataType: 'json',
        success: (data) => {
           this.reset();
           alert('Files has been uploaded using jQuery ajax');
        },
        error: function(data){
           alert(data.responseJSON.errors.files[0]);
           console.log(data.responseJSON.errors);
         }
       });
   });
});

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

Step 7 – Ajax Code to Upload Multiple File

In this step, implement the jQuery code to display or show multiple image preview before upload using ajax in laravel 8:

<script type="text/javascript">
     
$(document).ready(function (e) {
   
   $.ajaxSetup({
       headers: {
           'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
   });
   
  
   $('#multi-file-upload-ajax').submit(function(e) {

     e.preventDefault();
  
      var formData = new FormData(this);

      let TotalFiles = $('#files')[0].files.length; //Total files
      let files = $('#files')[0];
      for (let i = 0; i < TotalFiles; i++) {
          formData.append('files' + i, files.files[i]);
      }
      formData.append('TotalFiles', TotalFiles);
  
     $.ajax({
        type:'POST',
        url: "{{ url('store-multi-file-ajax')}}",
        data: formData,
        cache:false,
        contentType: false,
        processData: false,
        dataType: 'json',
        success: (data) => {
           this.reset();
           alert('Files has been uploaded using jQuery ajax');
        },
        error: function(data){
           alert(data.responseJSON.errors.files[0]);
           console.log(data.responseJSON.errors);
         }
       });
   });
});

</script>

Step 9 – Start Development Server

In this step, run the following command on cmd to start the development server:

php artisan serve

Then start this app on browser, so open your browser and fire the following url into browser:

http://127.0.0.1:8000/multi-file-ajax-upload

Recommended Laravel Posts

RELATED ARTICLES

Most Popular

Recent Comments