Uploading files is a common task in web development, but it can be a pain to implement. Fortunately, Laravel makes it easy to upload files with Ajax and show a progress bar. In this tutorial, we’ll go over how to implement Laravel 10 Ajax File Upload with Progress Bar.
Steps for Laravel 10 Ajax File Upload with Progress Bar
- Set up a new Laravel project
- Install the required dependencies
- Create a form for file upload
- Create a controller for file upload
- Add routes for file upload
- Add the Filepond plugin
- Initialize Filepond
- Handle file upload with Ajax
- Show a progress bar
Step 1: Set up a new Laravel project
To get started, you’ll need to create a new Laravel project. You can do this by running the following command in your terminal:
laravel new project-name
Step 2: Install the required dependencies
Next, you’ll need to install the required dependencies for the file upload functionality. In this case, we’ll be using the laravel-filepond
package.
To install this package, run the following command:
composer require codeteam/laravel-filepond
After installing the package, you’ll need to publish the configuration file by running the following command:
php artisan vendor:publish --provider="CodeTeam\Filepond\FilepondServiceProvider" --tag="config"
This will create a new filepond.php
file in your config
directory. You can customize the configuration options in this file if needed.
Step 3: Create a form for file upload
Next, you’ll need to create a form for file upload. In this tutorial, we’ll be using a simple form with a file input and a submit button. Here’s the code for the form:
<form action="{{ route('upload') }}" method="POST" enctype="multipart/form-data">
@csrf
<input type="file" name="file">
<button type="submit">Upload</button>
</form>
This form will submit the file to the upload
route using the POST
method. We’ve also included the @csrf
directive to protect against cross-site request forgery attacks.
Step 4: Create a controller for file upload
Now that we have a form for file upload, we’ll need to create a controller to handle the upload. Here’s the code for the controller:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
class UploadController extends Controller
{
public function index()
{
return view('upload');
}
public function store(Request $request)
{
$path = $request->file('file')->store('uploads');
return response()->json(['path' => $path]);
}
}
This controller has two methods: index
and store
. The index
method simply returns the view with the file upload form. The store
method handles the actual file upload. It uses the store
method provided by Laravel’s Storage
class to store the file in the storage/app/uploads
directory. Finally, it returns a JSON response with the path to the uploaded file.
Step 5: Add routes for file upload
Now that we have a controller for file upload, we’ll need to add routes to handle the upload. Here’s the code for the routes:
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UploadController;
Route::get('/', [UploadController::class, 'index'])->name('upload');
Route::post('/upload', [UploadController::class, 'store'])->name('upload.store');
These routes map the GET /
route to the index
method of the UploadController
, which displays the file upload form. They also map the POST /upload
route to the store
method of the UploadController
, which handles the file upload.
Step 6: Add the Filepond plugin
Now that we have the backend set up to handle file uploads, we’ll need to add the Filepond plugin to the frontend. Filepond is a JavaScript library for handling file uploads with Ajax and showing a progress bar.
To add Filepond to your project, you can use a package manager like npm
or yarn
. Run the following command to install Filepond and its dependencies:
npm install filepond filepond-plugin-file-validate-size filepond-plugin-file-validate-type filepond-plugin-image-exif-orientation filepond-plugin-image-preview
After installing the dependencies, you’ll need to add the following code to your view:
<input type="file" name="filepond" class="filepond" multiple>
This creates a file input with the filepond
class, which Filepond will use to initialize the plugin. You’ll also need to include the JavaScript and CSS files for Filepond. You can do this by adding the following code to your view:
<link href="https://unpkg.com/filepond/dist/filepond.css" rel="stylesheet">
<script src="https://unpkg.com/filepond/dist/filepond.min.js"></script>
<script src="https://unpkg.com/filepond-plugin-file-validate-size/dist/filepond-plugin-file-validate-size.min.js"></script>
<script src="https://unpkg.com/filepond-plugin-file-validate-type/dist/filepond-plugin-file-validate-type.min.js"></script>
<script src="https://unpkg.com/filepond-plugin-image-exif-orientation/dist/filepond-plugin-image-exif-orientation.min.js"></script>
<script src="https://unpkg.com/filepond-plugin-image-preview/dist/filepond-plugin-image-preview.min.js"></script>
This includes the core Filepond script as well as the plugins for validating file size and type, fixing image orientation, and previewing images.
Step 7: Initialize Filepond
Now that we’ve added the Filepond plugin to the frontend, we’ll need to initialize it with JavaScript. Here’s the code for initializing Filepond:
FilePond.registerPlugin(
FilePondPluginFileValidateSize,
FilePondPluginFileValidateType,
FilePondPluginImageExifOrientation,
FilePondPluginImagePreview
);
const inputElement = document.querySelector('input[type="file"]');
const pond = FilePond.create(inputElement);
This code registers the Filepond plugins and creates a Filepond instance with the file input element. We’ve also included the input[type="file"]
selector to target the file input with the filepond
class.
Step 8: Handle file upload with Ajax
Now that we’ve initialized Filepond, we’ll need to handle the file upload with Ajax. Here’s the code for handling the upload:
pond.setOptions({
server: {
url: '/upload',
process: {
url: '/',
method: 'POST',
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}',
},
onload: (response) => {
console.log(response);
},
},
revert: {
url: '/',
method: 'DELETE',
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}',
},
},
},
});
This code sets the options for the Filepond instance, including the server URL and the upload and revert methods. We’ve also included the CSRF token to protect against cross-site request forgery attacks.
Step 9: Show a progress bar
Finally, we’ll need to show a progress bar to the user during the file upload. Here’s the code for showing a progress bar:
pond.setOptions({
server: {
url: '/upload',
process: {
url: '/',
method: 'POST',
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}',
},
onload: (response) => {
console.log(response);
},
onprogress: (file, progress) => {
console.log(file, progress);
},
},
revert: {
url: '/',
method: 'DELETE',
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}',
},
},
},
});
pond.on('processfile', (error, file) => {
if (error) {
console.log(error);
return;
}
console.log(file);
const progress = pond.getFile(file.id).getProgress();
if (progress === 1) {
console.log('Upload complete');
} else {
console.log('Upload in progress');
}
});
This code sets the onprogress
option for the upload process, which will be called as the file is uploaded. We’ve also included an event listener for the processfile
event, which will be triggered when the file upload is complete. In this event listener, we check the progress of the file and log a message indicating whether the upload is complete or in progress.
Conclusion
In this tutorial, we’ve gone over how to implement Laravel 10 Ajax File Upload with Progress Bar. We started by setting up a new Laravel project and installing the required dependencies. Then, we created a form for file upload and a controller to handle the upload. Next, we added routes to handle the upload and the Filepond plugin to the frontend. We then initialized Filepond and handled the file upload with Ajax, and finally, we showed a progress bar to the user during the upload. With these steps, you should now be able to implement file upload with Ajax and a progress bar in your Laravel projects.