Laravel and Angular js file upload

陌路散爱 提交于 2019-12-02 04:45:31

I am using below code to upload image try this, I hope it works for you too.

<-- Front end file input -->

<input type="file" name="file" onchange="angular.element(this).scope().uploadavtar(this.files)"/>

<-- Angular Controller's File -->

$scope.uploadavtar = function(files) {
  var fd = new FormData();
  //Take the first selected file
  fd.append("file", files[0]);

  $http.post("/uploadavtar", fd, {
      withCredentials: true,
      headers: {'Content-Type': undefined },
      transformRequest: angular.identity
  }).then(function successCallback(response) {
    alert(response);
    // this callback will be called asynchronously
    // when the response is available
  }, function errorCallback(response) {
    alert(response);
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });
}

<-- In Route File -->

Route::post('/uploadavtar', 'UsersController@uploadavtar');

<-- In UsersController -->

public function uploadavtar(Request $request){
$user = JWTAuth::parseToken()->authenticate();
$user_id = $user->id;
$user_name = $user->first_name." ".$user->last_name;

$file = array('image' => Input::file('file'));
// setting up rules
$rules = array('image' => 'required',); //mimes:jpeg,bmp,png and for max size max:10000
// doing the validation, passing post data, rules and the messages
$validator = Validator::make($file, $rules);
if ($validator->fails()) {
  // send back to the page with the input data and errors
  return "validation failed";
}else {
    // checking file is valid.
    if (Input::file('file')->isValid()) {
      $destinationPath = 'assets/img'; // upload path
      $extension = Input::file('file')->getClientOriginalExtension(); // getting image extension
      $fileName = rand(11111,99999).'.'.$extension; // renameing image
      Input::file('file')->move($destinationPath, $user_name."_$user_id".".jpeg"); // uploading file to given path
      // sending back with message
      return 'Upload successfully';
    }
    else {
      // sending back with error message.
      return 'uploaded file is not valid';
    }
}
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!