php代码
//执行图片上传
public function upload($field){
//获取请求的数据
$file=request()->file($field);
$info=$file->move(STATIC_PATH.'/upload/images/'.$field);
//$info=$file->move(ROOT_PATH.'public'.DS.'static'.DS.'super'.DS.'image'.DS.$field);
if($info){
$system_logo = Db::name('setting') ->where('site_id', 0) ->value('system');
if($system_logo){
// 更换图片后查询原有图片地址并删除
$console=str_replace('\\\\','/',$system_logo);
$system_logo=str_replace('"','',$console);
if(is_file(STATIC_PATH.'/upload/images/system_logo/'.$system_logo)){
unlink(STATIC_PATH.'/upload/images/system_logo/'.$system_logo);
}
}
return json(['code'=>1000,'msg'=>'上传成功','data'=>$info->getSaveName()]);
}else{
return json(['code'=>1001,'msg'=>$file->getError(),'data'=>'']);
}
}
//添加站点
public function addSite(){
if(request()->isPost()){
$request=htmlspecialchars_decode(input('val'));
$req=json_decode($request,true);
if(!empty($req['header_pic'])){
$data['avatar']=$req['header_pic'];
}
$data['create_time']=time();
$db=Db::name('site')->insert($data);
if($db){
return json(['code'=>1000,'msg'=>'添加成功']);
}else{
return json(['code'=>1001,'msg'=>'添加失败']);
}
}
}
html代码
<div class="layui-form-item">
<label class="layui-form-label">头像:</label>
<div class="layui-input-block">
<button type="button" class="layui-btn" id="uploadClick">
<i class="layui-icon"></i>上传图片
</button>
<div class="layui-upload-list">
<img class="layui-upload-img" width="100px" height="100px" id="showPic" src="">
</div>
<input type="hidden" value="" name="header_pic" id="pichidden">
</div>
</div>
<script type="text/javascript">
layui.use(['form','upload'],function(){
var table=layui.table;
var upload=layui.upload;
form.on("submit(addziliao)",function(obj){
fields=JSON.stringify(obj.field);
$.ajax({
type:'post'
,url:"__URL__/addSite"
,data:{val:fields}
,success:function(data){
layer.msg(data.msg,{icon:2})
}
})
layer.closeAll();
return false;
})
upload.render({
elem:"#uploadClick",
url:"__URL__/upload?field=header_pic",
accept:"images",//允许上传的文件类型
acceptMime:"image/jpg,image/png,image/jpeg",//打开文件选择框时允许显示的文件类型
exts:'jpg|png|jpeg',//允许上传的文件后缀
size:1020,//允许上传的文件大小 单位kb
auto:true,//选中文件自动上传
field:'header_pic',
before:function(obj){
//预览
obj.preview(function(index,file,result){
$('#showPic').attr('src',result);
})
},done:function(res){
if(res.code==1000){
$('#pichidden').attr('value',res.data);
layer.msg(res.msg,{icon:1});
}else{
layer.msg(res.msg,{icon:2});
}
}
})
})
</script>
扩展:
Excel:
accept: 'file',
acceptMime: 'application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
exts: 'xlsx|xls', //只允许上传excel文件
CSV:
accept: 'file',
acceptMime: '.csv',
exts: 'csv', //只允许上传csv文件
TXT:
accept: 'file',
acceptMime: 'text/plain',
exts: 'txt', //只允许上传txt文件