2016-01-15 4 views
1

Как я могу сохранить изображения с laravel и угловыми js? больше входов, но эта работа для меня, имеют тип текстаLaravel and Angular js file upload

Мой индекс:

<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> 

Мой маршрут:

Route::get('admin/bar', '[email protected]'); 
Route::resource('/bar', 'BarController'); 

Моя модель:

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: общественная функция магазин() {

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

App.js (Угловая 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(); 

}); 
+0

ли вы решить эту проблему? – georgeos

ответ

1

Я использую ниже код для загрузки изображения попробовать это, я надеюсь, это сработает и для вас.

< - Фронтальный входной конец файла ->

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

< - Файл угловых Контролера ->

$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. 
    }); 
} 

< - В Маршрут Файл ->

Route::post('/uploadavtar', '[email protected]'); 

< - В 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'; 
    } 
} 
} 
+0

Как я могу добавить сюда? $ scope.addTodo = function() { \t \t $ scope.loading = true; \t \t $ http.post ('/ событие', { \t \t \t Название: $ scope.todo.name, \t \t \t старт: $ scope.todo.start, \t \t \t Описание: $ Объем. todo.description, \t \t \t фото: $ scope.todo.photo, \t \t \t сделано:. $ scope.todo.done \t \t}) успех (функция (данные, статус, заголовки, конфигурации) { \t \t \t $ scope.todos.push (данные); \t \t \t $ scope.todo = ''; \t \t \t $ scope.load = false; \t \t}); \t}; –

+0

Вышеупомянутое решение работает. Я предпочел вместо rand (11111,99999) использовать время(). –