准备资料
下载layui
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>图片上传</title>
<link rel="stylesheet" href="layui-v2.2.5/layui/css/layui.css" media="all">
</head>
<body>
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
<legend>上传多张图片</legend>
</fieldset>
<div class="layui-upload">
<button type="button" class="layui-btn" id="test2">多图片上传</button>
<blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;">
预览图:
<div class="layui-upload-list" id="demo2"></div>
</blockquote>
</div>
<script src="layui-v2.2.5/layui/layui.js"></script>
<script src="layui-v2.2.5\layui\jquery-3.3.1.min.js"></script>
<script>
layui.use('upload', function () {
var upload = layui.upload;
//多图片上传
upload.render({
elem: '#test2',
url: 'imgdemo',
multiple: true,
before: function (obj) {
//预读本地文件示例,不支持ie8
obj.preview(function (index, file, result) {
$('#demo2').append('<img src="' + result + '" alt="' + file.name +
'" class="layui-upload-img">')
});
},
done: function (res) {
//如果上传失败
if (res.code == 404) {
return layer.msg(res.msg);
}
//上传成功
if (res.code == 1) {
return layer.msg(res.photo);
}
}
});
});
</script>
</body>
</html>
tp5 代码:
public function imgdemo(Request $request){
//接收上传的文件
$file = $this->request->file('file');
if(!empty($file)){
//图片存的路径
$imgUrl= ROOT_PATH . 'public' . DS . 'uploads'. '/' . date("Y/m/d");
// 移动到框架应用根目录/public/uploads/ 目录下
$info = $file->validate(['size'=>1048576,'ext'=>'jpg,png,gif'])->rule('uniqid')->move($imgUrl);
$error = $file->getError();
//验证文件后缀后大小
if(!empty($error)){
dump($error);exit;
}
if($info){
// 成功上传后 获取上传信息
//获取图片的名字
$imgName = $info->getFilename();
//获取图片的路径
$photo=$imgUrl . "/" . $imgName;
}else{
// 上传失败获取错误信息
$file->getError();
}
}else{
$photo = '';
}
if($photo !== ''){
return ['code'=>1,'msg'=>'成功','photo'=>$photo];
}else{
return ['code'=>404,'msg'=>'失败'];
}
}
效果图如下
服务端
注意(报错可能是资源引用路径错误)