文件上传可以直接引用框架自定义的文件上传类 use think\File;
这里封装一个文件上传的model,以便重复利用 UploadFiles.php
1、控制器层
use app\admin\model\UploadFiles; // 使用文件上传model
2、model层
<?phpnamespace app\admin\model;use think\Model; // 使用Modeluse 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; }}
转载于:https://www.cnblogs.com/lpblogs/p/7277366.html
相关资源:TP5.0 多图 上传 无刷新 预览