Laravel Ajax Image Upload with Validation Example

By Hardik Savani November 5, 2023 Category : Laravel

Hey Artisan,

Today, I would like to show you laravel ajax image upload. I explained simply step by step laravel jquery file upload. Here you will learn php laravel jquery ajax image upload. I’m going to show you about jquery ajax image upload laravel example. Let's see below example ajax file uploading laravel.

You always did file uploading in a normal way and you can do it easily. But when you have a large amount of file size then it takes time to upload on a server. Maybe you can't reduce the time to upload a file or image, but you can display a progress bar with a percentage, so the client can understand how much time is left to upload a file.

in this tutorial, we will create two routes with the FileController controller file. when you click on submit button then fire the jquery ajax method and the upload of the image will show you a progress bar. let's follow the below step to do this example.

Step 1: Install Laravel

This step is not required; however, if you have not created the laravel app, then you may go ahead and execute the below command:

composer create-project laravel/laravel example-app

Step 2: Create Routes

In first step, we will add new two routes. One for display view and we will write jquery code in view file. In Second step, we will create POST route for file upload.

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\FileController;

/*

|--------------------------------------------------------------------------

| 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::controller(FileController::class)->group(function(){

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

Route::post('file-upload', 'store')->name('file.upload');

});

Step 3: Create FileController

In second step, we need to create FileController controller with index() and store(). you need to create "files" folder in public folder. we will store all files on that folder. just create new controller and put bellow code on it:

app/Http/Controllers/FileController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Illuminate\View\View;

use Illuminate\Http\JsonResponse;

class FileController extends Controller

{

/**

* Show the application dashboard.

*

* @return \Illuminate\Http\Response

*/

public function index(): View

{

return view('fileUpload');

}

/**

* Show the application dashboard.

*

* @return \Illuminate\Http\Response

*/

public function store(Request $request): JsonResponse

{

$request->validate([

'file' => 'required',

]);

$fileName = time().'.'.request()->file->getClientOriginalExtension();

request()->file->move(public_path('files'), $fileName);

return response()->json(['success'=>'You have successfully upload file.']);

}

}

Step 4: Create Blade File

In this Last step, we require to create fileUpload.blade.php file and we write code for jquery and show you with progress bar. So you have to simply add bellow code on following path:

resources/views/fileUpload.blade.php

<!DOCTYPE html>

<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>Laravel Bootstrap 5 Progress Bar Example - ItSolutionStuff.com</title>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet">

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

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.3.0/jquery.form.min.js"></script>

</head>

<body>

<div class="container mt-5" style="max-width: 900px">

<div class="bg-dark p-4 text-center rounded-3 mb-2">

<h2 class="text-white m-0">Laravel File Upload with Ajax Progress Bar Example - ItSolutionStuff.com</h2>

</div>

<!-- Starting of successful form message -->

<div class="row">

<div class="col-12">

<div class="alert alert-success success__msg bg-dark" style="display: none; color: white;" role="alert">

Uploaded File successfully.

</div>

</div>

</div>

<!-- Ending of successful form message -->

<div class="card bg-transparent border rounded-3 mb-5 p-5">

<form id="fileUploadForm" method="POST" action="{{ route('file.upload') }}" enctype="multipart/form-data">

@csrf

<div class="form-group mb-3">

<input name="file" type="file" class="form-control">

</div>

<div class="form-group">

<div class="progress">

<div class="progress-bar progress-bar-striped progress-bar-animated bg-dark" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%"></div>

</div>

</div>

<div class="d-grid mt-4">

<input type="submit" value="Upload" class="btn btn-dark">

</div>

</form>

</div>

</div>

<script>

$(function () {

$(document).ready(function () {

var message = $('.success__msg');

$('#fileUploadForm').ajaxForm({

beforeSend: function () {

var percentage = '0';

},

uploadProgress: function (event, position, total, percentComplete) {

var percentage = percentComplete;

$('.progress .progress-bar').css("width", percentage+'%', function() {

return $(this).attr("aria-valuenow", percentage) + "%";

})

},

complete: function (xhr) {

console.log('File has uploaded');

message.fadeIn().removeClass('alert-danger').addClass('alert-success');

message.text("Uploaded File successfully.");

setTimeout(function () {

message.fadeOut();

}, 2000);

form.find('input:not([type="submit"]), textarea').val('');

var percentage = '0';

}

});

});

});

</script>

</body>

</html>

Run Laravel App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:

php artisan serve

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8000/file-upload

Output:

I hope it can help you...

Tags :
Shares