欢迎访问WDPHP素材源码!今天是2024年04月30日 星期二,上午工作顺利吗?
您好,游客 [ 马上登录 | 注册帐号 | 微信登录 | QQ登录]
当前位置:首页 > 教程 > PHP教程 > 

THINKPHP6 自定义文件上传命名规则
栏目分类:PHP教程    发布日期:2023-01-09    浏览次数:1871次     收藏

先看看THINKPHP默认的文件名生成方法

    /**
     * 自动生成文件名
     * @access public
     * @param string|\Closure $rule
     * @return string
     */
    public function hashName($rule = ''): string
    {
        if (!$this->hashName) {
            if ($rule instanceof \Closure) {
                $this->hashName = call_user_func_array($rule, [$this]);
            } else {
                switch (true) {
                    case in_array($rule, hash_algos()):
                        $hash           = $this->hash($rule);
                        $this->hashName = substr($hash, 0, 2) . DIRECTORY_SEPARATOR . substr($hash, 2);
                        break;
                    case is_callable($rule):
                        $this->hashName = call_user_func($rule);
                        break;
                    default:
                        $this->hashName = date('Ymd') . DIRECTORY_SEPARATOR . md5(microtime(true) . $this->getPathname());
                        break;
                }
            }
        }

        return $this->hashName . '.' . $this->extension();
    }

THINKPHP默认提供了三种上传命名规则:

规则 描述
date 根据日期和微秒数生成
md5 对文件使用md5_file散列生成
sha1 对文件使用sha1_file散列生成

实现方法

public function upload(){
    // 获取表单上传文件 例如上传了001.jpg
    $file = request()->file('image');
    // 接收示例一
    // 上传到本地服务器   默认上传到runtime/storage目录下面生成以当前日期为子目录
    $fileName = \think\facade\Filesystem::putFile( 'image', $file,'命名规则:如md5,date,sha1三种选其一,默认md5');
    //接收示例二
    // 如果是多应用的话,上传根目录默认是runtime/index/storage,如果你希望上传的文件是可以直接访问或者下载的话,可以使用public存储方式。
    $fileName = \think\facade\Filesystem::disk('public')->putFile( 'image', $file,'命名规则:如md5,date,sha1三种选其一,默认md5');
}

可以通过自定义函数或闭包函数实现自定义上传文件名

闭包方式:

$FilePath = \think\facade\Filesystem::disk('public')->putFile($path, $file,function() use($file){
            return date('Y/m/d') . DIRECTORY_SEPARATOR . md5(microtime(true) . $file->getPathname());
        });

自定义函数

array('date', 'Ymd'), //子目录创建方式,[0]-函数名,[1]-参数,多个参数使用数组

$FilePath = \think\facade\Filesystem::disk('public')->putFile($path, $file,array('date', 'Ymd'));

声明:本文为原创文章,如需转载,请注明来源 WDPHP.COM 并保留原文链接:http://www.wdphp.com/detail/1992.html
源码 模板 特效 素材 资源 教程 站长