1. 程式人生 > >【PHP工具類】Upload

【PHP工具類】Upload

author:咔咔

wechat:fangkangfk

 

使用案例:

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

 

<?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;
    }
}