Laravel 5.2 ajax文件上传不接收文件


Laravel 5.2 ajax file upload does not receives file

我有一个Laravel 5.2应用程序,我试图通过ajax上传一些文件,但Laravel没有收到它们。

这是我的代码:

function uploadImages(selector){
var file_data = selector.prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
jQuery.ajax({
    url: '/uploadfile/', 
    dataType: 'json',
    cache: false,
    contentType: false,
    processData: false,
    data: form_data,                         
    type: 'POST',
    success: function(php_script_response){
        console.log(php_script_response);
    }, 
    error: function(jqXHR, textStatus, errorThrown){
        console.log(textStatus);
        console.log(errorThrown);
    }
});
}

以下是php部分:

public function uploadPhoto(Request $request){
    $string = str_random(40);
    $response = [];
    $file = $request->file('file');
    $response['str'] = $file;
    return response()->json($response);
}

问题是,$文件是NULL。(成功功能将Object { str: "NULL" }打印到控制台)。

我检查了控制台"网络"选项卡中发送的标题,图像似乎是按预期发送的。有人知道吗?

更新:

这是html表单:

<form action="" method="post" enctype="multipart/form-data">
    <input type='file' id='choosePhoto' name='file'>
</form>

我建议使用这个jquery插件:http://malsup.com/jquery/form/#file-上传

将此添加到您的js:

    $('#my-form').ajaxForm({
            beforeSubmit: function(formData, jqForm, options){
                // just like jquery ajax
            },
            success: function(responseText, statusText, xhr, $form){
                console.log(responseText);
            },
            clearForm: true //clear form after submit
        });

然后根据您的看法:

<form id="my-form" method="POST" action="{{ URL::to('my/route') }}" enctype="multipart/form-data">
    <input type="file" name="image" accept="image/*" required>
    <input class="subir" type="submit" name="submit" value="Upload">
    {{ csrf_field() }}
</form>

从上面的代码中,我理解的问题不是laravel上传程序,而是jquery片段。在jquery中,您必须以不同的方式处理文件上传。请在这里找到关于创建一个片段以通过ajax/jquery上传文件的教程