2014-09-02 114 views
1

我使用dropzone.js将图像上传到我的网站,但Laravel总是报告TokenMismatchException,尽管我在表单中使用了Form::open(),它自动添加了_tokenLaravel-Tokenmissmatchexception with Dropzone.js

这是我的代码:

{{ Form::open(["class" => "dropzone", "id" => "imgUpload", "action" => "[email protected]"]) }} 
    <div class="fallback"> 
     {{ Form::submit() }} 
    </div> 
{{ Form::close() }} 

JS

Dropzone.options.imgUpload = { 
     paramName: "file", 
     dictDefaultMessage: "Pošalji sliku", 
     acceptedFiles: "image/*", 
     previewsContainer: ".dropzone-previews", 
     uploadprogress: function(progress, bytesSent){ 
      console.log(progress); 
    } 
}; 

如何解决这个问题?

+0

您是否在'UploadsController'构造函数中设置了任何过滤器?即...'$ this-> beforeFilter()' – user3158900 2014-09-02 15:45:44

+0

我在路由中添加了全局保护:Route :: when('*','csrf',array('post','put','delete')); – Alen 2014-09-02 15:47:55

回答

1

看起来好像Dropzone在通过AJAX发布时不包括令牌。您可以使用这样的事情让它做这样....

Dropzone.options.imgUpload = { 
    paramName: "file", 
    dictDefaultMessage: "Pošalji sliku", 
    acceptedFiles: "image/*", 
    previewsContainer: ".dropzone-previews", 
    uploadprogress: function(progress, bytesSent) { 
     console.log(progress); 
    }, 
    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", $('[name=_token']).val()); // Laravel expect the token post value to be named _token by default 
     } 
}; 

,我发现这里的一段:http://laravel.io/forum/04-17-2014-tokenmismatchexception-with-dropzonejs

它也像有一些问题,令牌和形式通过提交AJAX。在这种情况下,当初始化dropzone时,您会希望包含额外的标头。

Dropzone.options.imgUpload = { 
    paramName: "file", 
    dictDefaultMessage: "Pošalji sliku", 
    acceptedFiles: "image/*", 
    previewsContainer: ".dropzone-previews", 
    headers: { 
     "X-CSRF-Token": $('[name=_token').val()) 
    }, 
    uploadprogress: function(progress, bytesSent) { 
     console.log(progress); 
    } 
}; 

,并利用这一点,修改filters.php你CSRF过滤器以检查头,如果我们是通过AJAX提交。

Route::filter('csrf', function() 
{ 
    $token = Request::ajax() ? Request::header('X-CSRF-Token') : Input::get('_token'); 

    if (Session::token() != $token) { 
     throw new Illuminate\Session\TokenMismatchException; 
    } 
}); 
+0

我以前试过,但它是一样的。当我打开FireBug时,我可以看到dropzone正在发送_token,并且当我包含您的代码时,它会发送_token两次,所以必须有另一个问题。 – Alen 2014-09-02 16:01:18

+0

我只是将meta标记中的token与dropzone ajax请求中的标记进行比较,它们完全相同,因此可能是什么问题。 – Alen 2014-09-02 16:30:28

+0

我可能有另一个想法,你可以更新你的问题,但包括你的CSRF过滤器? – user3158900 2014-09-02 17:16:15