简体   繁体   中英

How to upload file using Ajax In Laravel I am getting error 419 (unknown status)

How to upload file using Ajax In Laravel I am getting error 419 (unknown status). 1.Javascript Code. 2.Controller Code. 3.Router Code.

Javascript Code

$("#front_image").change(function() {
  let photo = document.getElementById("front_image").files[0];
  let formData = new FormData();
  formData.append("photo", photo);
  formData.append("names",'ABC');

  $.ajax({
      type: "POST",
      url:'/up',
      data:{"_token": $('meta[name="csrf-token"]').attr('content'),"formdata":formData},
      cache:false,
      contentType: false,
      processData: false,
      success:function(data){
          console.log("success");
         console.log(data);
      },
      error: function(data){
          console.log("error");
          console.log(data);
      }
  });
});

Controller Code

public function Image(Request $request) {
  return $request->get('names');
}

Router Code

Route::POST('/up', 'Controller@Image')

Try to add the CSRF-Token to your header like this:

$("#front_image").change(function() {
  let photo = document.getElementById("front_image").files[0];
  let formData = new FormData();
  formData.append("photo", photo);
  formData.append("names",'ABC');

  $.ajax({
    headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
    type: "POST",
    url: '/up',
    data: formData,
    cache: false,
    contentType: false,
    processData: false,
    success: function(data){
      console.log("success");
      console.log(data);
    },
    error: function(data){
      console.log("error");
      console.log(data);
    }
  });
});

Furthermore i would prefer to add the formData like this example above. So you can access it the way you did in your controller.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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