標籤:gif request log mode 圖片路徑 檔案上傳 idt 技術分享 function
檔案上傳可以直接引用架構自訂的檔案上傳類 use think\File;
這裡封裝一個檔案上傳的model,以便重複利用 UploadFiles.php
1、控制器層
use app\admin\model\UploadFiles; // 使用檔案上傳model
2、model層
<?php
namespace app\admin\model;
use think\Model; // 使用Model
use think\File; // 使用檔案上傳類
use think\Validate; // 使用檔案上傳驗證
use think\Request; // 接值時使用
/**
* 封裝檔案上傳model
*/
class UploadFiles extends Model
{
/**
* 單檔案上傳
* @param [type] $file [description]
* @return [type] string [description]
*/
public function uploadOne($file){
$filePath = ROOT_PATH . ‘public‘ . DS . ‘uploads‘; // 項目實體路徑
$rootPath = Request::instance()->root(true); // 項目根路徑
if (!file_exists($filePath)) {
mkdir($filePath);
}else{
$info = $file
->validate([
‘size‘=>156780,
‘ext‘=>‘jpg,png,gif‘
])
->move($filePath);
if($info){
// 輸出 20160820/42a79759f284b767dfcb2a0197904287.jpg
return $rootPath."/uploads/".$info->getSaveName(); // 返回帶網域名稱的圖片路徑
// 輸出 42a79759f284b767dfcb2a0197904287.jpg
// return $info->getFilename();
}else{
return $file->getError();
}
}
}
/**
* 多檔案上傳
* @param [type] $files [description]
* @return [type] array [description]
*/
public function uploadAll($files)
{
$filePath = ROOT_PATH . ‘public‘ . DS . ‘uploads‘; // 項目實體路徑
$rootPath = Request::instance()->root(true); // 項目根路徑
$array = array();
foreach ($files as $key => $file) {
if (!file_exists($filePath)) {
mkdir($filePath);
}else{
$info = $file
->validate([
‘size‘=>156780,
‘ext‘=>‘jpg,png,gif‘
])
->move($filePath);
if($info){
// 輸出 20160820/42a79759f284b767dfcb2a0197904287.jpg
$imgPath = $rootPath."/uploads/".$info->getSaveName(); // 返回帶網域名稱的圖片路徑
array_push($array,$imgPath);
// 輸出 42a79759f284b767dfcb2a0197904287.jpg
// return $info->getFilename();
}else{
return $file->getError();
}
}
}
return $array;
}
}
TP5單檔案、多檔案上傳