ThinkPHP5+Layui实现图片上传加预览

时间:2018-05-15
QQ截图20170928104410

前端文件:

<label class="layui-form-label">图片</label>
<a class="layui-btn" id="image" style="float: left;"><i class="layui-icon">&#xe67c;</i>上传图片</a>
<div class="layui-input-block" style="margin-left: 220px;">
  <input type="text" name="img" value="{$tptc.img}" class="layui-input" style="position: absolute;left: 0;top: 0;">
</div>
</div>

<div class="layui-form-item">
  <img style="margin-left: 110px;" id="img" src="{$tptc.img}">
</div>

<script>
layui.use('upload',function(){
  var upload = layui.upload,
  jq = layui.jquery;
  upload.render({
	url: '{:url("index/upload")}'
	,elem:'#image'
	,ext: 'jpg|png|gif'
	,area: ['500', '500px']
	,before: function(input){
	loading = layer.load(2, {
	shade: [0.2,'#000']
	});
	}
	,done: function(res){
	layer.close(loading);
	jq('input[name=img]').val(res.path);
	img.src = ""+res.path;
	layer.msg(res.msg, {icon: 1, time: 1000});
	}
  }); 

})
</script>


后台文件:

public function upload(){
    // 获取表单上传文件 例如上传了001.jpg
    $file = request()->file('file');
    // 移动到框架应用根目录/public/uploads/ 目录下
    $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
    if($info){
	// 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
	$path =  $info->getExtension();
        // 成功上传后 返回上传信息
	return json(array('state'=>1,'path'=>$path));
    }else{
        // 上传失败返回错误信息
	return json(array('state'=>0,'errmsg'=>'上传失败'));
    }
}

上一条:layui文件上传实现代码分享 下一条:PHP生成随机字符串

相关文章

最新文章