Skip to content
Advertisement

How do i pass csrf token with this file upload

I have this html:

<input id="input-id" type="file" accept=".mp3, .mp4" name="file" class="form-control"><br>
<input type="hidden" id="getfilename" name="uploadedfile" value="">

And this jquery plugin to upload file:

$("#input-id").fileinput({
        maxFileSize: 264000,
        uploadUrl: "{{url('/rate/uploadfile')}}", 
        uploadAsync: true,
        allowedFileExtensions: ['mp3', 'mp4', 'mpeg', 'flv'],
        maxFileCount: 1,
        showUpload: true,
        dropZoneEnabled: false
});

And the route under web middleware group:

Route::post('rate/uploadfile', 'RateController@uploadfile');

And whenever i try to upload the file i got the familiar error:

TokenMismatchException in VerifyCsrfToken.php

Advertisement

Answer

First add this code on your form <input type="hidden" id="csrf_token" name="_token" value="{{ csrf_token() }}"> this adds a csrf token field on your form using laravel’s csrf_token() function. Then on your script add this

    $("#input-id").fileinput({
            maxFileSize: 264000,
            uploadUrl: "{{url('/rate/uploadfile')}}", 
            uploadAsync: true,
            uploadExtraData:{'_token':$('#csrf_token').val()
            allowedFileExtensions: ['mp3', 'mp4', 'mpeg', 'flv'],
            maxFileCount: 1,
            showUpload: true,
            dropZoneEnabled: false
    });

If you are using http://plugins.krajee.com/file-input this plugin for the file upload then uploadExtraData:{'_token':$("#csrf_token").val()}, this line should add the csrf token as an extra post parameter for the ajax request. Hope this helps.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement