环境:layui2.9.21\thinkphp8.1
前端代码:
layui.use(['upload', 'layer'], function() {const upload = layui.upload;const layer = layui.layer;const $ = layui.$;// 上传图片const uploadInstImage = upload.render({elem: '#uploadImage',url: '/admin/demo/uploadImage', // 上传接口accept: 'images', // 只允许上传图片multiple: true, // 开启多文件上传;unified: true, // 统一上传,只请求后端api一次;field: 'file[]', // 一定要带上[];done: function (res) {if (res.code === 0) {$('#imagePath').val(res.data.path); // 将路径填入隐藏字段layer.msg('上传成功');} else {layer.msg('上传失败:' + res.msg);}},error: function () {layer.msg('上传失败,请重试');}});});
后端代码:
use think\facade\Filesystem;
use think\response\Json;
use think\response\View;
use app\admin\validate\Upload; // 创建了图片上传验证器;public function uploadImage(): Json{$files = request()->file('file'); // 一定和前端的字段名称保持一致;$validate = new Upload();$result = $validate->check(['image' => $files]);if (!$result) {return json(['code' => 500, 'msg' => $validate->getError()]);}try {$filepath = []; // 存储上传成功后的文件路径,以数组的形式保存;// 遍历$filesforeach ($files as $file) {$filepath[] = Filesystem::disk('public')->putFile('', $file);}return json(['code' => 200, 'msg' => 'success', 'data' => ['path' => str_replace('\\', '/', $filepath)]]);} catch (\Exception $e){return json(['code' => 500, 'msg' => $e->getMessage()]);}}