如何在laravel控制器中获取ajax post方法发送的formdata值


How to get formdata values sent by ajax post method in laravel controller

我试图使用formdata通过ajax发送一组数据,包括图像文件,但当我想访问laravel控制器中的数据时,它显示了一个空白数组。

这是我的ajax代码-

var fd = new FormData();
    fd.append("photo",files[0]);
    fd.append("user_id",localStorage.getItem('userId'));
    fd.append("doctype","dl_image");       
    console.log(fd);

   //ajax code
    $http.post('uploadfile', fd, {    
            withCredentials: true,      
            headers: { 'X-CSRF-TOKEN' : $('meta[name="csrf-token"]').attr('content') }       
     }).success(function(data, status) {        
               console.log(data);

     });

PHP代码-

    $data = Request::all();
    $photo = Request::file('photo');
    $userid = Request::get('user_id');
    $doctype = Request::get('doctype');

    $postData = array(
        'photo' => $photo,
        'user_id' => $userid,
        'doctype' => $doctype  
    );
    var_dump($data);
    die();

当数据转储到浏览器控制台时,它显示

array(0) {
}

需要帮助。

AngularJS使用application/json类型&默认情况下为JSON正文
所以我认为你需要使用:

headers: { 'Content-Type' : 'application/x-www-form-urlencoded'},
data: $.param(data)

在CCD_ 3代码中
您可能需要使用类似$name = Input::get('name');的东西,而不是$userid = Request::get('user_id');

使用FormData API对文件和数据进行POST时,将Content-Type头设置为undefined非常重要。

尝试:headers: { 'Content-Type': undefined }

请尝试序列化jquery的方法。

function myForm( form ){
    var formData = $(form).serialize();
    att=form.attr("action") ;
    $.post(att, formData).done(function(data){
        alert(data);
    });
    return true;
}