[TOC]
前言
今天在公司無(wú)事,就搞了下文件上傳的東東箕宙,方便自己的學(xué)習(xí)嚎朽,和今后的使用,目前只支持單文件上傳柬帕。下面是代碼部分哟忍,也可以訪問(wèn)我的 Gitee 或 Github,不想看代碼的童鞋可以直接[下載]陷寝。锅很。。(算了凤跑,討厭百度云爆安,如果有需要的話留言)代碼使用,使用方法請(qǐng)點(diǎn)擊
代碼
<?php
namespace E;
class FileUpload
{
/**
* @var $name 上傳文件標(biāo)記名
*/
protected $name = 'file';
/**
* @var $ext 所允許的擴(kuò)展名
*/
protected $exts = [];
/**
* @var $file 上傳的文件資源
*/
protected $file = null;
/**
* @var $upload_success 是否上傳成功標(biāo)志
*/
protected $upload_success = false;
/**
* @var $max_size 上傳文件所允許的大小仔引,單位為 M
*/
protected $max_size = 2;
/**
* @var $error_code 錯(cuò)誤碼
*/
protected $error_code = 0;
/**
* @var $error_msg 錯(cuò)誤信息
*/
protected $error_msg = '';
/**
* @var $file_ext 文件擴(kuò)展名
*/
protected $file_ext = '';
/**
* @var $type 文件類型扔仓,默認(rèn)為任意類型
*/
protected $type = 'file';
protected const ERR_OK = 0;
protected const ERR_FILE_SIZE = 1;
protected const ERR_FORM_SIZE = 2;
protected const ERR_PARTIAL = 3;
protected const ERR_NO_FILE = 4;
protected const ERR_FILE_EXIST = 5;
protected const ERR_NO_TMP_DIR = 6;
protected const ERR_CANT_WRITE = 7;
protected const ERR_FILE_TYPE = 8;
/**
* 配置上傳信息
*
* @param array $arr
* @return E\FileUpload
*/
public function config($arr)
{
foreach ($arr as $key => $val) {
if (property_exists($this, $key)) {
$this->$key = $val;
}
}
return $this;
}
/**
* 進(jìn)行文件上傳操作
*
* @return E\FileUpload
*/
public function upload()
{
$this->file = $this->getFile();
$this->file_ext = strrchr($this->file['name'], '.');
$this->upload_success = !($this->uploadError() || $this->overMaxSize() || $this->notAllowType());
return $this;
}
/**
* 判斷文件是否上傳成功
*
* @return boolean
*/
public function uploadSuccess()
{
return $this->upload_success;
}
/**
* 保存已上傳的文件
*
* @param string $path
* @param string $file_name
*
* @return boolean
*/
public function save($path, $file_name = '')
{
if (!$this->uploadSuccess()) {
return false;
}
// 判斷文件夾是否存在褐奥,如果不存在,新建一個(gè)文件夾
if (!is_dir($path)) {
mkdir($path);
}
// 獲取文件名翘簇,不包含后綴
$file_name = $file_name ?: 'e_' . time() . mt_rand(10000, 99999);
$file = rtrim($path, '/') . '/' . $file_name . $this->file_ext;
// 判斷文件是否存在
if (file_exists($file)) {
$this->error_code = self::ERR_FILE_EXIST;
return false;
}
if (move_uploaded_file($this->file['tmp_name'], $file)) {
return true;
}
// 文件未上傳成功撬码,出現(xiàn)未知錯(cuò)誤
$this->error_code = -1;
return false;
}
/**
* 返回錯(cuò)誤碼
*
* @return integer
*/
public function errorCode()
{
return $this->error_code;
}
/**
* 返回錯(cuò)誤信息
*
* @return string
*/
public function errorMsg()
{
!$this->error_msg && $this->setErrorMsgByCode($this->error_code);
return $this->error_msg;
}
/**
* 獲取上傳文件
*
* @return mixed
*/
protected function getFile()
{
return $_FILES[$this->name];
}
/**
* 判斷是否上傳錯(cuò)誤
*
* @return boolean
*/
protected function uploadError()
{
$this->error_code = $this->file['error'];
return (bool)$this->file['error'];
}
/**
* 根據(jù)錯(cuò)誤代碼設(shè)置錯(cuò)誤信息
*
* @param int $code
*/
protected function setErrorMsgByCode($code)
{
$msg_arr = [
'',
'上傳文件最大為 ' . $this->getMaxSize() . 'M',
'上傳文件過(guò)大',
'文件只有部分被上傳',
'沒(méi)有文件被上傳',
'文件已存在',
'文件丟失',
'文件寫(xiě)入失敗',
'只能上傳' . implode(',', $this->exts) . '類型的文件'
];
$this->error_msg = $msg_arr[$code] ?? '未知錯(cuò)誤';
}
/**
* 獲取上傳文件所限制的最大大小
*
* @return int
*/
protected function getMaxSize()
{
return min($this->max_size, (int)ini_get('upload_max_filesize'));
}
/**
* 判斷文件是否超出限制大小
*
* @return boolean
*/
protected function overMaxSize()
{
if ($this->file['size'] > $this->getMaxSize() * 1024 * 1024 * 8) {
$this->error_code = self::ERR_FILE_SIZE;
return true;
}
return false;
}
/**
* 通過(guò)類型獲取后綴名數(shù)組
*
* @return array
*/
protected function getExtsByType()
{
$exts_arr = [
'image' => ['jpg', 'jpeg', 'png', 'gif'],
'file' => [],
'zip' => ['zip', 'rar', '7z']
];
return $exts_arr[$this->type] ?? [];
}
/**
* 判斷是否是允許的類型
*
* @return boolean
*/
protected function notAllowType()
{
$this->exts = $this->exts ?: $this->getExtsByType();
if (!$this->exts) return false;
if (preg_match('/^\.' . implode('|', $this->exts) . '$/i', $this->file_ext)) {
return false;
}
$this->error_code = self::ERR_FILE_TYPE;
return true;
}
}
使用方法
- 引入文件
include 'FileUpload.class.php';
- 實(shí)例化類
$uploader = new E\FileUpload();
- 配置
$uploader->config([
'name' => 'file',
'exts' => ['jpg'],
'type' => 'image',
'max_size' => 2,
]);
配置項(xiàng)的說(shuō)明:
配置項(xiàng) | 說(shuō)明 |
---|---|
name | 是 HTML 中 input 的 name,例如: <input type="file" name="file">版保,默認(rèn)是 file |
exts | 所允許上傳的文件擴(kuò)展名呜笑,類型為數(shù)組,默認(rèn)是任何類型的文件 |
type | 上傳文件類型彻犁,可以通過(guò)設(shè)置 type 屬性叫胁,設(shè)置允許上傳類型,默認(rèn)為 file袖裕, 目前可選類型有:file 全部文件類型曹抬,image 圖片類型, zip 壓縮包急鳄, 注意:exts優(yōu)先級(jí)高于 type谤民, 即如果設(shè)置了 type 為 file,exts 為 ['jpg'] 時(shí)疾宏,也還是只能上傳 jpg 類型的文件的 |
max_size | 所允許上傳的大小张足,單位為 M,默認(rèn)為 2M |
- 上傳
$uploader->upload();
- 保存
$uploader->save('./uploads/', 'test')
save 方法的返回值是一個(gè)布爾值坎藐,上傳成功返回 true为牍,失敗返回 false,可以根據(jù)返回的狀態(tài)進(jìn)行相應(yīng)的操作岩馍,如果失敗碉咆,可以使用 errorCode()
方法獲取錯(cuò)誤代碼,使用 errorMsg()
方法獲取錯(cuò)誤信息蛀恩。
save 方法的第一個(gè)參數(shù)為必填參數(shù)疫铜,是要保存的路徑,第二個(gè)參數(shù)是文件名双谆,可選壳咕,如果不填,則會(huì)自動(dòng)生成顽馋,生成規(guī)則: e_ 連接上當(dāng)前時(shí)間的時(shí)間戳再連接5位隨機(jī)數(shù)
也可以使用鏈?zhǔn)讲僮鳎?/p>
$uploader->upload()->save('./uploads/', 'test');
錯(cuò)誤碼說(shuō)明
錯(cuò)誤碼 | 說(shuō)明 |
---|---|
0 | 無(wú)錯(cuò)誤 |
1 | 上傳文件超出限制大小 |
2 | 上傳文件超出 form 表單所設(shè)置的 MAX_FILE_SIZE谓厘,也是文件過(guò)大 |
3 | 文件只有部分被上傳 |
4 | 沒(méi)有文件被上傳 |
5 | 存在同名文件 |
6 | 文件丟失 |
7 | 文件寫(xiě)入失敗 |
8 | 上傳的文件類型不被允許 |
-1 | 未知錯(cuò)誤 |