【问题标题】:TokenMismatchException when trying to use media-upload尝试使用媒体上传时出现 TokenMismatchException
【发布时间】:2015-08-27 04:30:52
【问题描述】:

我正在使用 Laravel 5.1 和 media-upload 包进行 ajax 图片上传。

https://github.com/triasrahman/laravel-media-upload

使用以下代码:

<input type="file" name="file">
<img clas="preview" src="">

$('input[name=file]').change(function()
{   
    // AJAX Request
    $.post( 'media-upload', {file: $(this).val()} )
        .done(function( data )
        {
            if(data.error)
            {
                // Log the error
                console.log(error);
            }
            else
            {
                // Change the image attribute
                $( 'img.preview' ).attr( 'src', data.path );
            }
        });
});

我收到 500 内部服务器错误。

正好符合这个问题:

https://github.com/triasrahman/laravel-media-upload/issues/1

但我并不完全了解如何让我的工作。我确实做了与添加的答案相同的代码。我仍然收到 500 错误。

我该如何解决这个问题?

【问题讨论】:

  • 你能把你的整个表格贴出来吗?

标签: php laravel csrf


【解决方案1】:

正如来自 github 的链接所说,您必须传递令牌。 _token : $("[name='_token']").val()

<input type="file" name="file">
<img clas="preview" src="">

$('input[name=file]').change(function()
{   
    // AJAX Request
    $.post( 'media-upload', {file: $(this).val(), _token : $("[name='_token']").val()} )
        .done(function( data )
        {
            if(data.error)
            {
                // Log the error
                console.log(error);
            }
            else
            {
                // Change the image attribute
                $( 'img.preview' ).attr( 'src', data.path );
            }
        });
});

【讨论】:

    【解决方案2】:

    如果你通过 ajax 提交表单,你必须这样添加它

    $.ajaxSetup({
        headers : {
            'X-CSRF-TOKEN' : $('meta[name="csrf-token"]').attr('content')
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多