laravelfile-uploadlaravel-bladeimage-uploadfilepond

419 error when uploading images in Laravel with filepond


The codes I used and wrote are as follows. I'm getting a 419 error when uploading a file.

create.blade.php

` // Get a reference to the file input element const inputElement = document.querySelector('input[name="image"]');

    // Create a FilePond instance
    const pond = FilePond.create(inputElement);
    const token =  $('meta[name="csrf-token"]').attr('content');
    
    FilePond.setOptions({
        server: {
            process: '{{ route('admin.tmp-file-pond-upload') }}',
            revert: '{{ route('admin.tmp-file-pond-delete') }}',
            header: {
                'X-CSRF-TOKEN': token,
            },
        },
    });`

web.php

Route::middleware('auth')->as('admin.')->group(function(){

    Route::post('tmp-filpond-upload', [AdminController::class, 'tmpFilepondUpload'])->name('tmp-file-pond-upload');
    Route::delete('tmp-filpond-delete', [AdminController::class, 'tmpFilepondDelete'])->name('tmp-file-pond-delete');

});

AdminController.php

`public function tmpFilepondUpload(Request $request)
{
    if ($request->hasFile('image')) {
        $image = $request->file('image');
        $fileName = $image->getClientOriginalName();
        return $fileName;
    }
}`

Even though I gave the csrf token in the headers, I could not get past the page expired error. There is a csrf token among the meta tags in app.blade.php. I use the csrf token there on different pages.

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


Solution

  • You need first define a header tag named "csrf-token" with your token in the content property (lets assume you already do that), then you need put the "header" inside "process", like this:

    <script type="module">
        const token =  $('meta[name="csrf-token"]').attr('content');
        
        process: {
            url: '/upload-url',
            method: 'POST',
            headers: {
                'X-CSRF-TOKEN': token,
            }
        }
    </script>
    

    Also, check the doc