Laravel 5.2 - 使用ajax上传图像

时间:2016-11-09 16:35:35

标签: javascript jquery ajax laravel-5.2

我尝试使用像这样的ajax上传图片:

ROUTE

Route::get('upload', 'PostController@addPhoto');

查看

<form action="" id="upload" enctype="multipart/form-data">                                         

<input type="file" id="file" name="file">

<input type="hidden" name="_token" value="{{csrf_token()}}" id="token">

<a href="#" class="btn-primary" id="submit">Upload</a>

</form>

CONTROLLER

public function addPhoto(Request $request){

        $file =  $request->file('file');
        //dd($file);
        return response()->json(['file'=>$file]);
}

JS

function upload(){

var token = $('#token').val();
var route =  "http://localhost:8000/upload";
var form = $('#upload')[0];
var formData = new FormData(form);

console.log(form);

     $.ajax({
      url: route,
      headers: {'X-CSRF-TOKEN': token},                          
      type: "GET",
      cache: false,
      dataType:'json',
      processData: false,
      contentType: false,
      data: {'file': formData},
      success:function(data){
      console.log(data);
       },
    });
}

var uploaded = document.querySelector('#submit').onclick= upload;

在我的控制器dd($file);中返回null。请问我该如何解决这个错误?我怎样才能很好地获得文件图像?也许ajax或形式有些错误?我想上传文件图片,谢谢你的帮助!

0 个答案:

没有答案