這是一份源碼php
<?php namespace app\data\util; use think\helper\Str; class UploadUtil { /** * @var 文件信息think\file這個類 */ private $file; /** * @var 上傳圖片的目錄 */ private $path; /** * 上傳文件規則 */ // protected $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); $save = str_replace('application/','',$save); // 判斷保存的目錄是否存在 if(!file_exists($save)){ mkdir($save,0777,true); } // 文件保存後的名字加類型 $image = $fileName['saveName'].'.'.$fileName['fileSuffix']; // 開始上傳 參數一:上傳路徑 參數二:文件名 $info = $file->validate(['size'=>20000000,'ext'=>'jpg,png,gif'])->move($save,$image); // 獲取上傳後的文件名 $this->path = $path.'/'.$image; # 去除public $this->path = str_replace('/public','',$this->path); if($info){ $resule = ['code'=>SUCCESS,'data'=>$this->path]; }else{ $resule = ['code'=>ERROR,'data'=>$file->getError()]; } return $resule; } /** * 配置保存路徑 * * @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; } }
在common文件中定義一個常量
而後在配置文件裏邊定義
數組
調用
app