我正在尝试通过dropzone上传图片,但是我得到了tokenmismatch错误,即使我在所需的地方添加了csrf令牌,我也非常绝望......
我的表单
{!! 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令牌放在我应该的地方它也不起作用吗?
谢谢你的时间。答案 0 :(得分:1)
只需在表单中放置隐藏字段,如
<input type="hidden" name="_token" value="{{csrf_token()}}">
您可以通过使用ajax调用(如
)传递令牌的值来使其不同$(function () {
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') }
});
});
答案 1 :(得分:0)
而不是创建有点脏的新元素。您可以将其包含在手动初始化dropzone中。
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的更详细集成,您可以参考本教程Integrating Dropzone.js in Laravel 5 applications