简体   繁体   English

Laravel 5-具有CSRF保护的AJAX图像上传

[英]Laravel 5 - AJAX image upload with CSRF protection

I have a form set up to upload an image. 我已设置要上传图片的表单。 I was previously using DropZone.js which worked fine and sent the CSRF token along with the ajax call. 我以前使用的是DropZone.js,它工作正常,并与ajax调用一起发送了CSRF令牌。 Everything server side is fine, but when trying to do this without DropZone I am getting token mismatch errors. 一切服务器端都很好,但是当尝试在没有DropZone的情况下执行此操作时,出现令牌不匹配错误。

This is my AJAX call: 这是我的AJAX呼叫:

    $(document).on('submit', ".hidden-image-upload", function(e){
    e.preventDefault();
    $.ajax({
        url:'/project/uploadImage',
        data:{
            data:new FormData($("#upload_form")[0]),
        },
        dataType:'json',
        async:false,
        type:'post',
        processData: false,
        contentType: false,
        success:function(response){
            console.log(response);
        },
    });
});

And this is the HTML: 这是HTML:

<form method="POST" action="http://localhost/project/create" accept-charset="UTF-8" class="hidden-image-upload">
    <input name="_token" type="hidden" value="5lgtt8AgbeF3lprptj8HNXVPceRhoJbqBeErBI1k">
    <input class="cover-image-upload-button" name="file" type="file">
</form>

How do I go about sorting out my AJAX call / Laravel to work together? 我该如何整理我的AJAX呼叫/ Laravel以便一起工作?

You can send the token in headers using $.ajax. 您可以使用$ .ajax在标头中发送令牌。

$(document).on('submit', ".hidden-image-upload", function(e){
    e.preventDefault();
    $.ajax({
        url:'/project/uploadImage',
        data:{
            data:new FormData($("#upload_form")[0]),
        },
        headers: {
           'X-CSRF-Token': $('form.hidden-image-upload [name="_token"]').val()
        }
        dataType:'json',
        async:false,
        type:'post',
        processData: false,
        contentType: false,
        success:function(response){
            console.log(response);
        },
    });
});

In the worst case, disable CSRF check in that route, just add the route in the array $except inside app/Http/Middleware/VerifyCsrfToken.php 在最坏的情况下,禁用该路由中的CSRF检查,只需将路由添加到$ app数组中,除了app / Http / Middleware / VerifyCsrfToken.php内

Try this. 尝试这个。 You must also pass your CSRF Token along with your FormData: 您还必须将CSRF令牌与FormData一起传递:

$(document).on('submit', ".hidden-image-upload", function(e){
e.preventDefault();

var data = new FormData($("#upload_form")[0]);
    data.append('_token', $('input[name="token"]').val());

$.ajax({
    url:'/project/uploadImage',
    data:{
        data: data,
    },
    dataType:'json',
    async:false,
    type:'post',
    processData: false,
    contentType: false,
    success:function(response){
        console.log(response);
    },
});

}); });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM