ThinkPHP6单文件上传封装

浏览1113

我们使用ThinkPHP6框架经常需要文件上传,以下是封装的单文件上传控制器,结合layui前端框架,实现上传,只需调用该方法,传递存储文件夹名,为何要传递文件夹名呢?实则是为了方便管理文件。

image.png

1、后端控制器代码:

<?php
/**
 *公共文件上传
 * User: Hm
 * Date: 2020/9/16
 * Email: <2938039696@qq.com>
 **/
declare (strict_types = 1);
namespace app\union\controller;
use think\exception\ValidateException;
class Upload extends Base
{
    /*
     * 单文件上传
     * */
    public function uploadImg(){
        //判断是否是POST请求,如果是处理上传逻辑
        if (request()->isPost()){
            //接收文件上传目录
            $namePath = request()->param('type');
            //获取表单上传文件
            $file = request()->file('file');
            $upload_dir = '/'.$namePath; //组装文件保存目录
            $suffix='jpg,jpeg,png,gif';  //文件格式
            $size='3'; //文件大小
            try {
                //验证器验证上传的文件
                validate(['file'=>[
                    //限制文件大小
                    'fileSize'      =>  $size * 1024 * 1024,
                    //限制文件后缀
                    'fileExt'       =>  'jpg,jpeg,png,gif'
                ]],[
                    'file.fileSize' =>  '上传的文件大小不能超过'.$size.'M',
                    'file.fileExt'  =>  '请上传后缀为:'.$suffix.'的文件'
                ])->check(['file'=>$file]);
 
                    //上传文件到本地服务器
                $filename = \think\facade\Filesystem::disk('public')->putFile($upload_dir, $file);
                ;
                if ($filename){
                    $src = '/uploads/'.str_replace('\\', '/', $filename);
                    return json(['code'=>1,'msg'=>'上传成功','data'=>['src'=>$src]]);
                }else{
                    return json(['code'=>0,'msg'=>'上传失败']);
                }
 
            }catch (ValidateException $e){
                return json(['code'=>0,'msg'=>$e->getMessage()]);
            }
        }else{
            return json(['code'=>0,'msg'=>'非法请求']);
 
        }
 
 
    }
}
?>

2、前端代码:

 <div class="layui-form-item layui-form-text">
                <label>ICON</label>
                <div>
                    <div id="test10">
                        <i></i>
                        <p>点击上传,或将文件拖拽到此处</p>
                        <div id="uploadDemoView" {php}if( isset($sys_config->sys_icon) != '' ) echo  'style ="display:block !important;" ';{/php}>
                            <hr>
                            <img src="{php}if( isset($sys_config->sys_icon) != '' ) echo  $sys_config->sys_icon ;{/php}" alt="上传成功后渲染" style="max-width: 196px">
                            <input type="hidden" name="sys_icon" id="sysIcon" value="{php}if( isset($sys_config->sys_icon) != '' ) echo  $sys_config->sys_icon ;{/php}">
                        </div>
                    </div>
                </div>
            </div>

3、Javascrpt代码:这里调用改方法并传递参数{type:'config'}

<script>
    layui.use(['upload','form'], function () {
        var form = layui.form
            ,layer = layui.layer
            ,upload = layui.upload
            ,$ = layui.$;
        //拖拽上传
        upload.render({
            elem: '#test10'
            ,url: '{:url("union.upload.uploadImg")}' //改成您自己的上传接口
            ,exts:'jpg|png|gif|bmp|jpeg'
            // ,auto:false
            // // ,field:''
            // ,bindAction:'#settingFile'
            ,data:{type:'config'}
            ,done: function(res){
                layer.msg('上传成功');
                layui.$('#uploadDemoView').removeClass('layui-hide').find('img').attr('src', res.data.src);
                layui.$('#sysIcon').attr('value', res.data.src);
                console.log(res)
            }
        });
});
</script>



  • 暂无任何回答