I am using Dropzone to upload images using Laravel 5. After Dropzone makes the put call to my URL I get the following error:
TokenMismatchException in VerifyCsrfToken.php line 67:
However, when I look at the payload for the request the token is present:
------WebKitFormBoundary91A7BYrMsDcGTEvx Content-Disposition: form-data; name="_method"
PUT ------WebKitFormBoundary91A7BYrMsDcGTEvx Content-Disposition: form-data; name="_token"
j3NbjibYF7k8g2w1P0enw6YVfDrDvCGKFMCFt4NX ------WebKitFormBoundary91A7BYrMsDcGTEvx Content-Disposition: form-data; name="title"
Here is my JS:
Dropzone.options.realDropzone = {
url: '/user/manage/10',
method: 'PUT',
paramName: 'file',
uploadMultiple: false,
parallelUploads: 100,
previewsContainer: '#dropzonePreview',
addRemoveLinks: true,
maxFiles: 10,
autoProcessQueue: false,
init: function () {
var dropZone = this;
this.element.querySelector("#save").addEventListener("click", function (e) {
e.preventDefault();
e.stopPropagation();
console.log("clicked submit");
dropZone.processQueue();
});
},
};
My form:
{!! Form::model($asset, ['method' => 'PUT', 'class' => 'dropzone', 'id' => 'real-dropzone', 'action' => ['UserManagementController@update', $asset->id], 'file' => true]) !!}
My controller:
public function update(Request $request, $id)
{
return dd(FileRequest::file('file'));
}
Try to add the token in your Dropzone options:
sending: function(file, xhr, formData) {
formData.append("_token", "{{ csrf_token() }}");
},
You can just add {{ csrf_field() }}
in your form
My working code for Laravel 5.6:
HTML
<div class="dropzone dropzone-previews" id="my-awesome-dropzone"></div>
jQuery
Dropzone.autoDiscover = false;
$(document).ready(function() {
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$("div#my-awesome-dropzone").dropzone({
url: "{{ url('/upload') }}",
headers: {
'x-csrf-token': CSRF_TOKEN,
},
});
});
HTML code in a blade file
<head>
…
<meta name="csrf-token" content="{{ csrf_token() }}">
</head>
<body>
<div class="dropzone" id="my-dropzone"></div>
</body>
JavaScript
Dropzone.autoDiscover = false;
new Dropzone('#my-dropzone', {
url: '/upload',
headers: {
'x-csrf-token': document.head.querySelector('meta[name="csrf-token"]').content,
},
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With