摘要
Laravel 使用 layui 文件上传组件批量上传图片。
layui是一款经典国产模块化前端UI框架,首先看看官方的介绍:
layui(谐音:类UI) 是一款采用自身模块规范编写的前端 UI 框架,遵循原生 HTML/CSS/JS 的书写与组织形式,门槛极低,拿来即用。其外在极简,却又不失饱满的内在,体积轻盈,组件丰盈,从核心代码到 API 的每一处细节都经过精心雕琢,非常适合界面的快速开发。layui 首个版本发布于金秋,她区别于那些基于 MVVM 底层的 UI 框架,却并非逆道而行,而是信奉返璞归真之道。准确地说,她更多是为服务端程序员量身定做,你无需涉足各种前端工具的复杂配置,只需面对浏览器本身,让一切你所需要的元素与交互,从这里信手拈来。
使用起来,还是很顺手的,因需要上传图片,就看看文件上传组件如何,首先看官方的文档
接下来就开始动手了,首先你需要准备好一个laravel应用,这里就不做介绍了,接着将下载好的layui文件夹放到应用的public目录中,结构基本如下:
然后我们写好前台文件,直接上代码,我直接写在默认的视图文件中
resources\views\welcome.blade.php
Laravel
.layui-upload-img
{
width: 92px;
height: 92px;
margin: 0 10px 10px 0;
}
高级应用:制作一个多文件列表
选择多文件
文件名大小状态操作
开始上传
预览图:
layui.use('upload', function(){
var $ = layui.jquery
,upload = layui.upload;
//多文件列表示例
var demoListView = $('#demoList')
,uploadListIns = upload.render({
elem: '#testList'
,url: '/upload'
,field:'photo'
,multiple: true
,auto: false
,headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
}
,bindAction: '#testListAction'
,choose: function(obj){
var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
//读取本地文件
obj.preview(function(index, file, result){
var tr = $(['
'
,'
'+ file.name +''
,'
'+ (file.size/1014).toFixed(1) +'kb'
,'
等待上传'
,'
'
,'重传'
,'删除'
,'
'
,'
'].join(''));
//单个重传
tr.find('.demo-reload').on('click', function(){
obj.upload(index, file);
});
//删除
tr.find('.demo-delete').on('click', function(){
delete files[index]; //删除对应的文件
tr.remove();
uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值,以免删除后出现同名文件不可选
});
demoListView.append(tr);
});
}
,done: function(res, index, upload){
if(res.code == 0){ //上传成功
console.log(res.ResultData);
$('#demo2').append('')
var tr = demoListView.find('tr#upload-'+ index)
,tds = tr.children();
tds.eq(2).html('上传成功');
tds.eq(3).html(''); //清空操作
return delete this.files[index]; //删除文件队列已经上传成功的文件
}
this.error(index, upload);
}
,error: function(index, upload){
var tr = demoListView.find('tr#upload-'+ index)
,tds = tr.children();
tds.eq(2).html('上传失败');
tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
}
});
});
然后新建控制器文件
\app\Http\Controllers\HomeController.php
新建如下方法
public function upload(Request $request)
{
$file = $request->file('photo');
// 获取文件路径
$transverse_pic = $file->getRealPath();
// public路径
$path = public_path('uploads');
// 获取后缀名
$postfix = $file->getClientOriginalExtension();
// 拼装文件名
$fileName = md5(time().rand(0,10000)).'.'.$postfix;
// 移动
if(!$file->move($path,$fileName)){
return response()->json(['ServerNo' => '400','ResultData' => '文件保存失败']);
}
// 这里处理 数据库逻辑
/**
*Store::uploadFile(['fileName'=>$fileName]);
**/
return response()->json(['code'=>0,'ServerNo' => '200','ResultData' => $fileName]);
}
注册路由
\routes\web.php
Route::post('/upload','HomeController@upload');
然后开始演示
可以看出整个过程还是很流畅的,操作起来体验很好。