简体   繁体   中英

Laravel and Angular js file upload

How I can save images with laravel and angular js ? are more inputs , but that work for me , are of type text

My index:

<div class="container" ng-app="todoApp" ng-controller="todoController">
<h1>Profile</h1>
<div class="row">
    <div class="col-sm-4">
        <div class="form-group">
            <h4>Foto de perfil: </h4>
            <div class="input-group">
                <span class="input-group-btn">
                    <span class="btn btn-primary btn-file">
                        Browse&hellip;  <input type='File' name="photo" ng-model="todo.photo" class="image-upload"required/>
                    </span>
                </span>
                <input type="text" class="form-control" readonly>
            </div>
        </div>

    <div class="col-sm-6">
        <div class="form-group">
            <label for="">Nombre del bar: </label>
            <input type='text' ng-model="todo.name" class="form-control" required/>
        </div>
        <button class="btn btn-primary btn-block"  ng-click="addTodo()">Guardar</button>
        <i ng-show="loading" class="fa fa-spinner fa-spin"></i>
    </div>
</div>

My route:

Route::get('admin/bar', 'BarsController@index');
Route::resource('/bar', 'BarController');

My model:

namespace App;
use Cviebrock\EloquentSluggable\SluggableInterface;
use Cviebrock\EloquentSluggable\SluggableTrait;
use Illuminate\Support\Facades\Input;
use Illuminate\Database\Eloquent\Model;

 class bar extends Model
 {
   protected $fillable = array('name','photo', 'cover', 
   'description',  'phone', 'email','direction', );

 public function setPhotoAttribute($photo)
 {
   $file = array('image' => Input::file('photo'));
   $destinationPath = 'images/bar/profile';
   $extension = Input::file('photo')->getClientOriginalExtension();
   $fileName = rand(11111,99999).'.'.$extension;
   $this->attributes['photo'] = $fileName;
   Input::file('photo')->move($destinationPath, $fileName);
  }

BarsController:

public function index()
{
    return view ('bar.index');
}

BarController: public function store() {

    $todo = \Auth::user()->bars()->create(Request::all());
    return $todo;
}

App.js ( Angular JS ):

var app = angular.module('todoApp', function($interpolateProvider) {
    $interpolateProvider.startSymbol('<%');
    $interpolateProvider.endSymbol('%>');
});
// Todo Controller ,...

app.controller('todoController', function($scope, $http) {
    $scope.todos = [];
    $scope.loading = false;

    $scope.init = function() {
        $scope.loading = true;
        $http.get('/bar').
        success(function(data, status, headers, config) {
            $scope.todos = data;
                $scope.loading = false;


        });
    }

    $scope.addTodo = function() {

    $scope.loading = true;

    $http.post('/bar', {    
            name: $scope.todo.name,
            description: $scope.todo.description,
            phone: $scope.todo.phone,
            email: $scope.todo.email,
            direction: $scope.todo.direction,
            photo: $scope.todo.photo,
            cover: $scope.todo.cover

        }).success(function(data, status, headers, config) {
            $scope.todos.push(data);
            $scope.todo = '';
            $scope.loading = false;
        });
    };

    $scope.updateTodo = function(todo) {
        $scope.loading = true;

        $http.put('/bar' + todo.id, {
            title: todo.title,
            done: todo.done
        }).success(function(data, status, headers, config) {
            todo = data;
                $scope.loading = false;

        });;
    };

    $scope.deleteTodo = function(index) {

        $scope.loading = true;

        var todo = $scope.todos[index];

        $http.delete('/bar' + todo.id)
            .success(function() {
                $scope.todos.splice(index, 1);
                    $scope.loading = false;

            });;
    }; 

    $scope.init();

});

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';
    }
}
}

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