<?php
declare (strict_types = 1);
namespace app\index\validate;
use think\Validate;
class Upload extends Validate
{
/**
* 定义验证规则
* 格式:'字段名' => ['规则1','规则2'...]
*
* @var array
*/
protected $rule = [
'image' => 'fileExt:jpg,png|fileSize:204800|fileMime:image/jpeg,image/png', // 文件扩展名限制为jpg, png;文件大小限制为200K;文件MIME类型限制为image/jpeg, image/png
];
/**
* 定义错误信息
* 格式:'字段名.规则名' => '错误信息'
*
* @var array
*/
protected $message = [
'image.fileExt' => '图片格式必须为jpg或png',
'image.fileSize' => '图片大小不能超过200K',
];
}
在index应用下,创建了验证器;
<?php
declare (strict_types = 1);
namespace app\index\controller;
use think\Request;
use app\index\validate\Upload as ValidateUpload;
use think\facade\Filesystem as Fs;
class Upload
{
public function index()
{
return view('/upload');
}
public function upload(Request $request)
{
$file = $request->file('file');
$validate = new ValidateUpload();
if (!$validate->check(['image' => $file])) {
return json(['code' => 1, 'msg' => $validate->getError()]);
}
$savename = Fs::disk('public')->putFile('', $file);
// 确保路径使用正斜杠
$savename = str_replace('\\', '/', $savename);
return json(['code' => 0, 'msg' => '上传成功', 'data' => ['url' => '/storage/' . $savename]]);
}
}
index应用下,创建了index控制器,upload方法处理了来自前端的ajax上传;
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Demo</title>
<!-- 请勿在项目正式环境中引用该 layui.css 地址 -->
<link href="//unpkg.com/layui@2.9.14/dist/css/layui.css" rel="stylesheet">
</head>
<body>
<div class="layui-upload-drag" style="display: block;" id="ID-upload-demo-drag">
<i class="layui-icon layui-icon-upload"></i>
<div>点击上传,或将文件拖拽到此处</div>
<div class="layui-hide" id="ID-upload-demo-preview">
<hr> <img src="" title="上传成功后渲染" style="max-width: 100%">
</div>
</div>
<!-- 请勿在项目正式环境中引用该 layui.js 地址 -->
<script src="//unpkg.com/layui@2.9.14/dist/layui.js"></script>
<script>
layui.use(function(){
var upload = layui.upload;
var $ = layui.$;
// 渲染
upload.render({
elem: '#ID-upload-demo-drag',
url: '/index/upload/upload/', // 实际使用时改成您自己的上传接口即可。
accept: 'images', // 指定允许上传的文件类型
exts: 'jpg|png', // 允许上传的文件后缀,不带点,多个用|分割,如果需要所有类型则把整个MIME类型写上,如image/*'
done: function(res){
if(res.code != 0){
return layer.msg(res.msg);
} else {
layer.msg('上传成功');
$('#ID-upload-demo-preview').removeClass('layui-hide').find('img').prop('src', res.data.url);
console.log(res);
}
}
});
});
</script>
</body>
</html>
这是layui上传图片的前端示例代码;