Laravel 9 Ajax Image Upload With Preview Tutorial

  • 25-08-2022
  • 974
  • Laravel 9
  • Haresh Chauhan

Laravel 9 Ajax Image Upload with Preview Tutorial; Upload Image Using jQuery Ajax With Preview In Laravel, This is important while you are working with the ajax in jquery with form data send also image or any other file upload things.

While we are working with ajax, that time send a request with data is a little simple thing, but when you want to send data along with the file or image that time it is a little bit difficult to send a request with FormData.

In this post, we will upload files using ajax and preview them with the help of laravel and ajax jquery. Simply we will use the jquery change event. so when you try to brows any image in the form and as you select will automatically upload file and preview itself.

Step 1. Create Laravel Project

Let's start by cloning a new laravel application. Use the below-provided command, Also you may change the project name as per your requirement. Goto terminal and run the command.

composer create-project --prefer-dist laravel/laravel ajax-file-upload

Go to your project directory using "cd" and then give your project name and hit enter in your terminal.

cd ajax-file-upload

Step 2. Create a Blade File

Create a blade file for the view input form in the browser. in this blade file, we will make a simple HTML form. In scrip, we will add a change event. as anything changes in form, the event will run. jQuery will fetch the form data and append it to FormData object.

Get Zipcode/Pincode From Latitude and Longitude Javascript and Google Maps API

Once the FormData object is successfully appended with a protected csrf token, will send the file FormData file object to the server side, and they will be uploaded a file in our local application storage folder and return the file upload path using this path we will show the image to the front below form.

resources/views/home.blade.php
<!doctype html>
<html lang="en">
    <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <title>Laravel 9 Ajax Image Upload with Preview Tutorial - Webappfix!</title>
    </head>
    <body>

    // HTML FORM
    <div class="container mt-5">
        <form action="#" id="file-upload-form">
            @csrf
            <div class="form-group">
                <input type="file" class="form-control" type="text" id="files">
            </div>
        </form>
        <div class="mt-3" id="img"></div>
    </div>
    // HTML FORM END

    <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
    <script>
        $(function(){
            $('#file-upload-form').change(function(){

                var form = new FormData();
                
                var files = $('#files')[0].files;

                form.append('file',files[0])
                form.append('_token',$('input[name=_token]').val())

                $.ajax({
                    type: "POST",
                    url: "{{ route('form.submit') }}",
                    data: form,
                    cache:false,
                    processData:false,
                    contentType:false,
                    success: function (response) {
                        $('#img').append('<img src="'+response.path+'" alt="image">');
                    },
                    error:function(error){
                        alert(error);
                    }
                });
            })
        })
    </script>
    </body>
</html>

Step 3. Define Routes

First create a Controller using suggested command.

php artisan make:controller HomeController

In this step we will define two routes, the first route will be from view, second route for the file upload from the ajax request.

routes/web.php
<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\HomeController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::view('form','home');
Route::post('form-submit',[HomeController::class,'formSubmit'])->name('form.submit');

Step 4. HomeController

Here is HomeController.php, we will code our file uploaded here. As an ajax request sending the route will redirect the request to this Homecontroller.php with the given method name in the route file.

jQuery load more data on scroll

Firstly we will upload the file from the coming request, it will return the storage path, suing this path we will make the image path URL from the image shown on the front page.

Once the URL is made successfully we will return to the JSON HTTP request with the success message. as the ajax receives the response in the blade file back the image will append to the div tage.

app/Http/Controllers/HomeController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\User;

use App\Rules\YoutubeValidLink;

use Validator;
use Storage;

class HomeController extends Controller
{
    public function formSubmit(Request $request)
    {
        $path = Storage::disk('public')->put('images',$request->file);
        
        $response = Storage::disk('public')->url($path);

        //  MAKE SURE YOUR STORAGE PUBLIC DISK PATH IS 

        // 'public' => [
        //     'driver' => 'local',
        //     'root' => storage_path('app/public'),
        //     'url' => env('APP_URL').'/storage/app/public', // ADD IN YOUR filesystems.php
        //     'visibility' => 'public',
        // ],
        
        return response()->json(['message' => 'File Uploded Successfully.','path' => $response]);
    }
}

Step 5. Start Development Server

Start your application development server by the suggested command in your terminal.

php artisan serve

Open your browser, and run the below-given URL in your browser.

http://127.0.0.1:8000/form

Laravel 9 Ajax Login Form Submit With Validation Handled


We always thanks to you for reading our blogs.


dharmesh-image

Dharmesh Chauhan

(Swapinfoway Founder)

Hello Sir, We are brothers origin from Gujarat India, Fullstack developers working together since 2016. We have lots of skills in web development in different technologies here I mention PHP, Laravel, Javascript, Vuejs, Ajax, API, Payment Gateway Integration, Database, HTML5, CSS3, and Server Administration. So you need our service Please Contact Us

haresh-image

Haresh Chauhan

(Co-Founder)


We Are Also Recommending You :