index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link rel="stylesheet" type="text/css" href="https://www.layuicdn.com/layui-v2.8.0/css/layui.css" /> <title></title> </head> <body> <div class="layui-form-item"> <label class="layui-form-label">上传图片</label> <div class="layui-input-block" id="image1"> <img src="https://www.layuicdn.com/index/images/desc.png" alt="" id="image2" style="height: 80px;width: 80px"> <input type="hidden" name="image" id="image"> </div> </div> <script src="https://www.layuicdn.com/layui-v2.8.0/layui.js"></script> <script> layui.use(['form', 'jquery', 'layer', 'upload'], function() { var $ = layui.jquery, form = layui.form, layer = layui.layer, upload = layui.upload; upload.render({ elem: '#image1', url: '/index/ceshi/image', accept: 'image', size: 3 * 1024, before: function(obj) {}, done: function(res) { if (res.status == 200) { layer.msg(res.msg, { icon: 1 }) $('#image2').attr('src', res.path) $('#image').val(res.path) } else { layer.msg(res.msg, { icon: 2 }) } } }); }) </script> </body> </html>
Thinkphp5控制器:
<?php declare (strict_types = 1); namespace app\index\controller; use think\facade\Request; use think\facade\Db; class Ceshi extends \app\BaseController{ public function index(){ return $this->fetch(); } /**图片上传*/ public function image(){ $file = request()->file('file'); // 移动到框架应用根目录/uploads/ 目录下 try{ // 验证 validate(['imgFile'=>[ 'fileSize' => 410241024, 'fileExt' => 'jpg,jpeg,png,bmp,gif', 'fileMime' => 'image/jpeg,image/png,image/gif', //这个一定要加上,很重要我认为! ]])->check(['imgFile' => $file]); // 上传图片到本地服务器 $saveName = \think\facade\Filesystem::disk('public')->putFile('',$file); $arr = ['status' => 200, 'msg' => '成功', 'path' => '/upload/'. $saveName]; return json($arr); } catch (\Exception $e) { // 验证失败 输出错误信息 return $this->exceptionHandle($e,'图片上传失败!' . $e->getMessage(),'json',''); } } }