Laravel和角度的js文件上传 [英] Laravel and Angular js file upload
本文介绍了Laravel和角度的js文件上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何保存laravel和角JS图片?
更投入,但对我的工作,是类型的文本
我的索引:
< DIV CLASS =容器NG-应用=todoAppNG控制器=todoController>
< H1>简介< / H1>
< DIV CLASS =行>
< DIV CLASS =COL-SM-4>
< DIV CLASS =表单组>
< H4>照片由PERFIL:LT; / H4>
< DIV CLASS =输入组>
<跨度类=输入组BTN>
<跨度类=BTN BTN-主要BTN文件>
浏览和放大器; hellip; <输入类型=文件NAME =照片NG模型=todo.photo级=图片上传要求/>
< / SPAN>
< / SPAN>
<输入类型=文本级=表格控只读>
< / DIV>
< / DIV> < DIV CLASS =COL-SM-6>
< DIV CLASS =表单组>
<标签=>农布雷德尔栏:其中; /标签>
<输入类型='文本'NG模型=todo.name级=表格控要求/>
< / DIV>
<按钮类=BTN BTN-主要BTN-块NG点击=addTodo()>&和保存LT; /按钮>
<我NG-秀=加载类=发发微调发旋>< / I>
< / DIV>
< / DIV>
我的路线:
路线::获得(管理/条','BarsController @指数');
路线::资源('/条','BarController');
我的模型:
命名空间应用;
使用Cviebrock \\ EloquentSluggable \\ SluggableInterface;
使用Cviebrock \\ EloquentSluggable \\ SluggableTrait;
使用照亮的\\ Support \\外立面\\输入;
使用照亮\\数据库\\锋\\型号; 一流的酒吧扩展模式
{
保护$ =可填写阵列(名称,照片,盖,
描述,电话,电子邮件,方向,); 公共职能setPhotoAttribute($照片)
{
$文件=阵列('形象'=>输入::文件('照片'));
$ =的DestinationPath图像/酒吧/ profile文件';
$扩展=输入::文件(照片) - GT; getClientOriginalExtension();
$文件名=兰特(11111,99999)$扩展。'。'。
$这个 - >属性['照片'] = $文件名;
输入::文件(照片) - GT;移动($的DestinationPath,$文件名);
}
BarsController:
公共功能指数()
{
返回视图(bar.index');
}
BarController:
公共职能店(){
$待办事项= \\验证::用户() - GT;酒吧() - GT;创建(支持::所有());
返回$待办事项;
}
App.js(角JS):
VAR应用= angular.module('todoApp',函数($ interpolateProvider){
$ interpolateProvider.startSymbol('<%');
$ interpolateProvider.endSymbol('%GT;');
});
//藤控制器,...app.controller('todoController',函数($范围,$ HTTP){
$ scope.todos = [];
$ scope.loading = FALSE; $ scope.init =功能(){
$ scope.loading = TRUE;
$ http.get('/条)。
成功(功能(数据,状态,头,配置){
$ scope.todos =数据;
$ scope.loading = FALSE;
});
} $ scope.addTodo =功能(){ $ scope.loading = TRUE; $ http.post('/条',{
名称:$ scope.todo.name,
说明:$ scope.todo.description,
电话:$ scope.todo.phone,
电子邮件:$ scope.todo.email,
方向:$ scope.todo.direction,
照片:$ scope.todo.photo,
盖:$ scope.todo.cover })。成功(功能(数据,状态,头,配置){
$ scope.todos.push(数据);
$ scope.todo ='';
$ scope.loading = FALSE;
});
}; $ scope.updateTodo =功能(待办事项){
$ scope.loading = TRUE; $ http.put('/条'+ todo.id,{
标题:todo.title,
完成:todo.done
})。成功(功能(数据,状态,头,配置){
待办事项=数据;
$ scope.loading = FALSE; });;
}; $ scope.deleteTodo =功能(指数){ $ scope.loading = TRUE; VAR待办事项= $ scope.todos [指数] $ http.delete('/条'+ todo.id)
.success(函数(){
$ scope.todos.splice(指数,1);
$ scope.loading = FALSE; });;
}; $ scope.init();});
解决方案
我使用低于code上传图片试试这个,我希望它为你的作品了。
< - 前端文件输入 - >
<输入类型=文件名称=文件的onchange =。angular.element(本).scope()uploadavtar(this.files)/>
< - 角控制器的文件 - >
$ scope.uploadavtar =功能(文件){
变种FD =新FORMDATA();
//在第一个选定的文件
fd.append(文件,文件[0]); $ http.post(/ uploadavtar,FD {
withCredentials:真实,
标题:{'内容类型':未定义},
transformRequest:angular.identity
})。然后(函数successCallback(响应){
警报(响应);
//这个回调函数将被异步调用
//当响应可用
},功能errorCallback(响应){
警报(响应);
//异步调用,如果发生错误
//或服务器返回的响应与一个错误状态。
});
}
< - 在路由文件 - >
路线::后('/ uploadavtar','UsersController @ uploadavtar');
< - 在UsersController - >
公共职能uploadavtar(请求$要求){
$ USER = JWTAuth :: parseToken() - GT;身份验证();
$ USER_ID = $用户自> ID;
$ USER_NAME = $用户自方式> FIRST_NAME,$用户自方式>姓氏;$文件=阵列('形象'=>输入::文件('文件'));
//设置规则
$规则=阵列('形象'=>'需要',); //默剧:JPEG,BMP,PNG和最大尺寸最大:10000
//做验证,通过后的数据,规则和信息
$验证=验证::彩妆($文件,$规则);
如果(用$ validator->失败()){
//发送回页面与输入数据和错误
返回验证失败;
}其他{
//检查文件是否有效。
如果(输入::文件(文件) - GT;的isValid()){
$ =的DestinationPath资产/ IMG'; //上传路径
$扩展=输入::文件(文件) - GT; getClientOriginalExtension(); //获取图像扩展
$文件名=兰特(11111,99999)$扩展。'。'。 // renameing图像
输入::文件(文件) - GT;移动($的DestinationPath,$ USER_NAME_ $ user_ID的。JPEG); //上传文件到指定路径
//发回的消息与
返回'成功上传';
}
其他{
//发回错误消息。
返回'上传的文件是无效的';
}
}
}
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… <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';
}
}
}
这篇关于Laravel和角度的js文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文