LayUI+Thinkphp5上传图片

LayUI   2025-01-26 13:43   76   0  

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>

<input type='button' id='selectFile' value='选择文件'>
<div id='fileDiv'></div>
<input type='button' id='uploadFile' value='上传文件'>
<div id="showpic"></div>

<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://www.layuicdn.com/layui-v2.8.0/layui.js"></script>
<script type="text/javascript">
$(function(){
    initUpload();
});
//初始化上传组件
function initUpload(){
    layui.use(['form', 'jquery', 'layer', 'upload'], function() {
        var $ = layui.jquery,
                form = layui.form,
                layer = layui.layer,
                upload = layui.upload;
        //单文件上传
        upload.render({
            elem: '#selectFile',
            url: "/index/ceshi/image",
            accept: 'file',
            multiple: false,
            auto: false,
            size: 50 * 1024,//单位kb
            bindAction: '#uploadFile',
            choose: function (obj) {
                console.log(obj)
                obj.preview(function (index, file, result) {
                    $("#fileDiv").val(file.name);
                });
            },
            done: function (res, index, upload) {
                console.log(res)
                if (res.status == 200) { //上传成功
                    $("#showpic").html("<img src="+res.path+" />");
                    alert("上传成功");
                }
                else {
                    alert("上传失败!");
                }
            },
            error: function (index, upload) {
                alert("上传失败!");
            }
        });
    });
}
    </script>
</body>
</html>


Thinkphp5控制器

/**图片上传*/
    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','');
        }
    }


博客评论
还没有人评论,赶紧抢个沙发~
发表评论
说明:请文明发言,共建和谐网络,您的个人信息不会被公开显示。