【PHP工具類】Upload

author:咔咔php

wechat:fangkangfk數組

 

使用案例:this

https://blog.csdn.net/fangkang7/article/details/85060379url

 

<?php

namespace data\util;

class Upload
{
    /**
     * @var 文件信息think\file這個類
     */
    private $file;
    /**
     * @var 上傳圖片的目錄
     */
    private $path;
    /**
     * 上傳文件規則
     */
    private $validate =[
        'size' => 500000,
        'ext'  => 'jpg,png,gif,jpeg',
    ];

    /**
     * 文件上傳
     *
     * @param file think\File
     * @path  上傳的目錄  upload\goods
     * @return array
     */
    public function move($file,$path)
    {
        $this->file = $file;
        // 獲取上傳的文件名
        $fileName = $this->getFileName($path);
        // 文件保存的地址
        $save = $this->getFilePath($path);
        // 判斷保存的目錄是否存在
        if(!file_exists($save)){
            mkdir($save,777,true);
        }
        // 文件保存後的名字加類型
        $image = $fileName['saveName'].'.'.$fileName['fileSuffix'];
        // 開始上傳  參數一:上傳路徑       參數二:文件名
        $info = $file->validata($this->validate)->move($save,$image);
        // 獲取上傳後的文件名
        $this->path = $save.'.'.$image;
        return ($info) ? true : false;
    }

    /**
     * 配置保存路徑
     *
     * @return array
     */
    public function getFilePath($path)
    {
        return ROOT.'/'.$path;
    }

    /**
     * 獲取上傳文件的信息  名字,類型,類型
     *
     * @return array
     */
    public function getFileName()
    {
        // 獲取文件信息
        $name = $this->file->getInfo('name');
        // 問件名1.jpg   因此須要轉數組獲取
        $fileName = explode('.',$name);
        return [
            // 文件名
            'formerlyName' => $fileName[0],
            // 保存後的文件名
            'saveName' => $fileName[0].time(),
            // 文件後綴
            'fileSuffix' => $fileName[1]
        ];
    }

    /**
     * 保存後的文件路徑
     *
     * @return array
     */
    public function functionName($flag = true)
    {
        return ($flag) ? $this->path : ROOT.'/'.$this->path;
    }
}
相關文章
相關標籤/搜索