[英]Laravel TokenMismatchException and dropzone
我正在嘗試通過dropzone上傳圖片,但是即使在需要的地方添加csrf令牌的情況下,我也遇到了tokenmismatch錯誤,我感到非常絕望...
我的表格
{!! Form::open(['route' => 'photo.upload', 'id' => 'hello', 'method' => 'POST', 'class' => 'dropzone no-margin dz-clickable']) !!}
<div class="dz-default dz-message"><span>Drop files here to upload</span></div></form>
{!! Form::close() !!}
我的劇本
Dropzone.autoDiscover = false;
Dropzone.options.hello = {
paramName: "file", // The name that will be used to transfer the file
maxFilesize: 5, // MB
parallelUploads: 2, //limits number of files processed to reduce stress on server
addRemoveLinks: true,
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content'),
},
accept: function(file, done) {
// TODO: Image upload validation
done();
},
sending: function(file, xhr, formData) {
// Pass token. You can use the same method to pass any other values as well such as a id to associate the image with for example.
formData.append("_token", $('input[name="_token"]').val() ); // Laravel expect the token post value to be named _token by default
},
init: function() {
this.on("success", function(file, response) {
// On successful upload do whatever :-)
});
}
};
// Manually init dropzone on our element.
var myDropzone = new Dropzone("#hello", {
url: $('#hello').attr('action')
});
請求頭
...
X-CSRF-Token:P4wc9NVVZJe1VjalPwO6d6WQXZ9eEqPd84ICpToG
...
請求有效載荷
------WebKitFormBoundarySKMUFNO6dbgzeQVK
Content-Disposition: form-data; name="_token"
P4wc9NVVZJe1VjalPwO6d6WQXZ9eEqPd84ICpToG
------WebKitFormBoundarySKMUFNO6dbgzeQVK
Content-Disposition: form-data; name="_token"
P4wc9NVVZJe1VjalPwO6d6WQXZ9eEqPd84ICpToG
------WebKitFormBoundarySKMUFNO6dbgzeQVK
Content-Disposition: form-data; name="file"; filename="Screen Shot 2016-01-14 at 18.27.40.png"
Content-Type: image/png
------WebKitFormBoundarySKMUFNO6dbgzeQVK--
當我查看生成的表單時,這里是csrf字段
<input name="_token" type="hidden" value="P4wc9NVVZJe1VjalPwO6d6WQXZ9eEqPd84ICpToG">
您是否知道即使我將crsf令牌放置在應有的位置也為什么不起作用?
感謝您的時間。
只需將隱藏字段放在表單中即可
<input type="hidden" name="_token" value="{{csrf_token()}}">
您可以通過使用ajax調用傳遞令牌的值來使其變得不同,例如
$(function () {
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') }
});
});
而不是創建有點臟的新元素。 您可以將其包含在dropzone的手動init中。
var myDropzone = new Dropzone("#hello", {
url: $('#hello').attr('action'),
headers: {
'x-csrf-token': document.querySelectorAll('meta[name=csrf-token]')[0].getAttributeNode('content').value,
}
});
有關與laravel dropzone的更詳細的集成,您可以參考本教程在Laravel 5應用程序中集成Dropzone.js。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.