TP6图片上传例子

2019-12-05   阅读:6564   分类:后端    标签: TP6

TP6的文件上传相较于之前的版本有些变化,用法变了,也相对的更灵活了。以下是简单的图片上传。

image.png


有问题可以在下面留言


前端代码

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form action="" enctype="multipart/form-data" method="post">
<input type="file" name="img" /> <br> 
<input type="submit" value="上传" /> 
</form> 
</body>
</html>

配置文件:filesystem.php

<?php

return [
    // 默认磁盘
    'default' => env('filesystem.driver', 'local'),
    // 磁盘列表
    'disks'   => [
        'local'  => [
            'type' => 'local',
            'root' => app()->getRuntimePath() . 'storage',
        ],
        'public' => [
            // 磁盘类型
            'type'       => 'local',
            // 磁盘路径
            'root'       => app()->getRootPath() . 'public/uploads',
            // 磁盘路径对应的外部URL路径
            'url'        => '/uploads/',
            // 可见性
            'visibility' => 'public',
        ],
        // 更多的磁盘配置信息
    ],
];

后端代码:

验证参数说明

fileSize上传文件的最大字节

fileExt文件后缀,多个用逗号分割或者数组

fileMime文件MIME类型,多个用逗号分割或者数组

image验证图像文件的尺寸和类型


    public function upload(){
       if(request()->isPost()){
         // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('img');
        try {
            // 使用验证器验证上传的文件
            validate(['file' => [
                // 限制文件大小(单位b),这里限制为4M
                'fileSize' => 4 * 1024 * 1024,
                // 限制文件后缀,多个后缀以英文逗号分割
                'fileExt'  => 'gif,jpg,png'
            ]])->check(['file' => $file]);
            // 上传到本地服务器
             $savename = \think\facade\Filesystem::disk('public')->putFile('img', $file);
             if($savename){
                // 拼接路径
                $path=\think\Facade\Filesystem::getDiskConfig('public', 'url').str_replace('\\', '/', $savename);
                $data['img']=$path;
                $res=Db::name('message')->order('id', 'desc')->insert($data);
                if($res){
                    return json(['code'=>200,'msg'=>'添加成功']);
                }else{
                    return json(['code'=>500,'msg'=>'添加失败']);
                }
             }
             // echo $savename;
        } catch (think\exception\ValidateException $e) {
            // echo $e->getMessage();
            return json(['code'=>500,'msg'=>$e->getMessage()]);
        }
       }
       return View::fetch();
    }


【腾讯云】 爆款2核2G3M云服务器首年 61元,2核2G4M云服务器新老同享 99元/年,续费同价

‘简忆博客’微信公众号 扫码关注‘简忆博客’微信公众号,获取最新文章动态
转载:请说明文章出处“来源简忆博客”。http://www.tpxhm.com/adetail/267.html

×
觉得文章有用就打赏一下文章作者
微信扫一扫打赏 微信扫一扫打赏
支付宝扫一扫打赏 支付宝扫一扫打赏

文章评论(0)

登录
简忆博客壁纸一
简忆博客壁纸二
简忆博客壁纸三
简忆博客壁纸四
简忆博客壁纸五
简忆博客壁纸六
简忆博客壁纸七
简忆博客壁纸八
头像

简忆博客
勤于学习,乐于分享

置顶推荐

打赏本站

如果你觉得本站很棒,可以通过扫码支付打赏哦!
微信扫码:你说多少就多少~
微信扫码
支付宝扫码:你说多少就多少~
支付宝扫码
×