- PHP
- /**
- * 上传文件类
- * Class UploadFile
- * 使用方法
- * $this->load->library('uploadfile',['path','jpg,png,pdf','2','file']);
- * $this->uploadfile->upload();
- * 数组参数 1: 目录 可不传 默认 class_upload_file
- * 数组参数 2: 允许上传的类型 可不传 默认 全部类型
- * 数组参数 3: 限制大小 (M) 可不传 不限制文件大小
- * 数组参数 4: $_FILES key 名称 可不传 默认 file
- */
- class UploadFile
- {
- protected $code = 0;
- protected $data = [];
- protected $msg = [ #错误返回提示
- '0' => '上传成功',
- '1' => '上传失败',
- '2' => '文件不存在',
- '3' => '文件 key 错误',
- '4' => '文件超过限制大小',
- '5' => '文件格式不正确',
- ];
- protected $path = 'class_upload_file'; # 文件目录
- protected $type = ''; # 文件类型
- protected $size = 0; # 文件大小限制 0 不限制
- protected $name = 'file';# 文件 KEY 名称
- protected $url = ''; # 返回路径
- /**
- * UploadFile constructor.
- * @param $params array($path,$size)
- */
- public function __construct($params)
- {
- $field = ['path', 'type', 'size', 'name'];
- if ($params) {
- foreach ($params as $key => $val) {
- $_field = $field[$key];
- !empty($params[$key]) && $this->$_field = $val;
- }
- }
- $this->url = '/upload/' . $this->path . '/';
- $this->path = str_replace("\\", '/', ROOTPATH) . $this->url;
- }
- /**
- * 错误返回
- * @param $code
- * @return array
- */
- protected function error($code)
- {
- return ['code' => '1', 'msg' => $this->msg[$code], 'data' => []];
- }
- /**
- * 成功返回
- * @param $data
- * @return array
- */
- protected function success($data)
- {
- return ['code' => 0, 'msg' => $this->msg[0], 'data' => $data];
- }
- /**
- * 判断文件是否存在
- */
- protected function checkFileExist()
- {
- empty($_FILES) && $this->code = 2;
- empty($_FILES[$this->name]) && $this->code = 3;
- }
- /**
- * 判断文件后缀是否符合
- */
- protected function checkFileType()
- {
- if ($this->type && !in_array(pathinfo($_FILES[$this->name]['name'], PATHINFO_EXTENSION), explode(',', $this->type)))
- $this->code = 5;
- }
- /**
- * 判断文件是否超过设置的大小
- */
- protected function checkFileSize()
- {
- if ($this->size> 0)
- $_FILES[$this->name]['size']> ($this->size * 1048576) && $this->code = 4;
- }
- /**
- * 判断文件夹是否存在
- */
- protected function filePathCreate()
- {
- if (!is_dir($this->path))
- mkdir($this->path, 0777, true);
- }
- /**
- * 文件上传
- */
- protected function saveFile()
- {
- $this->code = 1;
- if ($_FILES[$this->name]['error'] === 0) {
- $ext = strtolower(pathinfo($_FILES[$this->name]['name'], PATHINFO_EXTENSION));
- $fileName = md5(uniqid(microtime(true), true)) . "." . $ext;
- if (move_uploaded_file($_FILES[$this->name]['tmp_name'], $this->path . $fileName)) {
- $this->code = 0;
- return $this->data = [
- 'name' => $_FILES[$this->name]['name'],
- 'url' => $this->url . $fileName,
- ];
- }
- }
- }
- /**
- * 不限制文件类型
- * @return array
- */
- function upload()
- {
- $methods = ['checkFileExist', 'checkFileSize', 'checkFileType', 'filePathCreate', 'saveFile'];
- foreach ($methods as $method) {
- $this->$method();
- if ($this->code != 0)
- return $this->error($this->code);
- }
- return $this->success($this->data);
- }
- }
来源: http://www.bubuko.com/infodetail-3459903.html