1. 程式人生 > >TP5單文件、多文件上傳

TP5單文件、多文件上傳

don logs urn public ror space size del 返回

文件上傳可以直接引用框架自定義的文件上傳類 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單文件、多文件上傳