skevil's avatar

Image upload problem with Laravel 5.1

Hi everybody, this is my route:

Route::group(['prefix' => 'admin', 'namespace' => 'admin', 'middleware' => 'admin'], function() {
    Route::resource('test', 'TestController');
    Route::post('test/upload', 'TestController@doUpload');
});

and this is the doUpload function:

    $this->validate($request, [
            'file'  => 'image'
        ]);
        ...
    ...
        $request->file('file')->move(base_path() . '/public/upload/test/'. sha1(time()));

For the front-end I use Dropzone.js with this code

<form action="{{ url('/admin/test/upload')}}" class="dropzone" id="my-awesome-dropzone"></form>

The problem is that when I select a file, the route is called but the function isn't executed. The console print this: [500]: /admin/auction/upload Where am I wrong?

0 likes
5 replies
skevil's avatar

In the configuration of Dropzone I set this:

headers: {
            "X-CSRF-Token": "{{ csrf_token() }}"
}

How can I check if the token is valid or not in Laravel?

sutherland's avatar

Is your Dropzone configuration in a blade template, or a separate JS file? If it's in a separate file you'll need to add

<meta name="csrf_token" content="{{ csrf_token() }}">

to the head section of your template file and use

"X-CSRF-Token":  document.querySelector('meta[name="csrf_token"]').getAttribute('content')

in your JS file.

skevil's avatar

Dropzone configuration is in layout/master.blade.php which contains the head and the footer of the site.

skevil's avatar
skevil
OP
Best Answer
Level 1

Here is the solution (It worked for me):

Add this in the head

<meta name="csrf_token" content="{{ csrf_token() }}">

and in the Dropzone configuration add this

init: function() {
    this.on("sending", function(file, xhr, formData) {
        formData.append("_token", $('[name="csrf_token"]').attr('content'));
    });
}

Please or to participate in this conversation.