【ThinkPHP】最新版本上传文件的类

小破孩
2024-10-26 / 0 评论 / 54 阅读 / 正在检测是否收录...
<?php
namespace app\common\lib\file;
use think\Exception;
use think\exception\ValidateException;

class Uploads
{
    private $domain;
    protected $name;
    protected $type;
    protected $module;
    protected $image;

    public function __construct($name = '',$image = [])
    {
        $this->name   = $name;
        $this->module = app('http')->getName();
        $this->image  = $image;
        $this->domain = Request()->domain();
    }

    protected $config = [
        'image' => [
            'validate' => [
                'size' => 10*1024*1024,
                'ext'  => 'jpg,png,gif,jpeg',
            ],
            'path'     =>  '/images',
        ],
        'audio' => [
            'validate' => [
                'size' => 100*1024*1024,
                'ext'  => 'mp3,wav,cd,ogg,wma,asf,rm,real,ape,midi',
            ],
            'path'     =>  '/audios',
        ],
        'video' => [
            'validate' => [
                'size' => 100*1024*1024,
                'ext'  => 'mp4,avi,rmvb,rm,mpg,mpeg,wmv,mkv,flv',
            ],
            'path'     =>  '/videos',
        ],
        'file' => [
            'validate' => [
                'size' => 5*1024*1024,
                'ext'  => 'doc,docx,xls,xlsx,pdf,ppt,pptx,txt,rar,zip,pem,p12',
            ],
            'path'     =>  '/files',
        ],
    ];

    private function determineFileType($file)
    {
        $mime = $file->getMime();
        if (strpos($mime, 'image/') === 0) {
            $this->type = 'image';
        } elseif (strpos($mime, 'video/') === 0) {
            $this->type = 'video';
        } elseif (strpos($mime, 'audio/') === 0) {
            $this->type = 'audio';
        } else {
            $this->type = 'file';
        }

        if (!in_array($this->type, array_keys($this->config))) {
            throw new ValidateException("the file type does not exist");
        }
        validate(['file' => self::validateFile()])->check(['file' => $file]);
    }


    public function upfile($infoSwitch = false,$savelocal = 'local'){
        try{
            $file = request()->file($this->name);
            //检测文件
            if($file == null) throw new ValidateException("the file cannot be empty");
            //验证文件
            $this->determineFileType($file);
            //上传文件
            switch ($savelocal){
                case 'aliyun':
                    $savename = \think\facade\Filesystem::disk('aliyun')->putFile( $this->module.$this->config[$this->type]['path'], $file);
                    break;
                case 'qiniu':
                    $savename = \think\facade\Filesystem::disk('qiniu')->putFile( $this->module.$this->config[$this->type]['path'], $file);
                    break;
                case 'qcloud':
                    $savename = \think\facade\Filesystem::disk('qcloud')->putFile( $this->module.$this->config[$this->type]['path'], $file);
                    break;
                case 'local':
                    $savename = \think\facade\Filesystem::disk('public')->putFile( $this->module.$this->config[$this->type]['path'], $file);
                    break;
                default :
                    $savename = \think\facade\Filesystem::disk('public')->putFile( $this->module.$this->config[$this->type]['path'], $file);
                    break;
            }
//            $savename = \think\facade\Filesystem::disk('public')->putFile( $this->module.$this->config[$this->type]['path'], $file);
//            $savename = \think\facade\Filesystem::disk('aliyun')->putFile( 'topic', $file);
            //返回文件详情和文件地址
            if($infoSwitch){
                return self::getFileInfo($file,$savename);
            }
            return $this->domain.config('filesystem.disks.public.url').'/'.str_replace('\\','/',$savename);
        }catch (\think\exception\ValidateException $e){
            return show(100,self::languageChange($e->getMessage()));
        }
    }

    private function validateFile(){
        if(empty($this->image)){
            $validataType = [
                'fileSize' => $this->config[$this->type]['validate']['size'],
                'fileExt'  => $this->config[$this->type]['validate']['ext'],
            ];
        }else{
            if(is_array($this->image)) throw new ValidateException("");
            $validataType = [
                'fileSize' => $this->config[$this->type]['validate']['size'],
                'fileExt'  => $this->config[$this->type]['validate']['ext'],
                'image'    => $this->image //示例值 [200,200]
            ];
        }
        return $validataType;
    }

    private function languageChange($msg){
        $data = [
            'the file type does not exist'               => '文件类型不存在!',
            'the file cannot be empty'                   => '文件不能为空!',
            'unknown upload error'                       => '未知上传错误!',
            'file write error'                           => '文件写入失败!',
            'upload temp dir not found'                  => '找不到临时文件夹!',
            'no file to uploaded'                        => '没有文件被上传!',
            'only the portion of file is uploaded'       => '文件只有部分被上传!',
            'upload File size exceeds the maximum value' => '上传文件大小超过了最大值!',
            'upload write error'                         => '文件上传保存错误!',
        ];
        return $data[$msg] ?? $msg;
    }

    private function getFileInfo($file,$savename){
        $info = [
            'path' => config('filesystem.disks.public.url').'/'.str_replace('\\','/',$savename),
            'url'  => $this->domain.config('filesystem.disks.public.url').'/'.str_replace('\\','/',$savename),
            'size' => $file->getSize(),
            'name' => $file->getOriginalName(),
            'mime' => $file->getMime(),
            'ext'  => $file->extension(),
            'type' => $this->type
        ];
        return $info;
    }

    public function __clone()
    {
        throw new Exception("Cloning operation is not allowed");
        // TODO: Implement __clone() method.
    }


// 使用方法 :
// $instanceUpload = new Uploads($fileName);
// $info = $instanceUpload->upfile(true);
}

如果要用建议封装一下,使用interface定义个规范,这里更像一个方法函数
0

评论

博主关闭了所有页面的评论