目錄
- 前言
- 代碼
- 使用方法
- 錯誤碼說明
前言
今天在公司無事,就搞了下檔案上傳的東東,方便自己的學習,和今后的使用,目前只支持單檔案上傳,下面是代碼部分,也可以訪問我的 Gitee 或 Github,不想看代碼的童鞋可以直接[下載],,,(算了,討厭百度云,如果有需要的話留言)代碼使用,使用方法請點擊
代碼
<?php
namespace E;
class FileUpload
{
/**
* @var $name 上傳檔案標記名
*/
protected $name = 'file';
/**
* @var $ext 所允許的擴展名
*/
protected $exts = [];
/**
* @var $file 上傳的檔案資源
*/
protected $file = null;
/**
* @var $upload_success 是否上傳成功標志
*/
protected $upload_success = false;
/**
* @var $max_size 上傳檔案所允許的大小,單位為 M
*/
protected $max_size = 2;
/**
* @var $error_code 錯誤碼
*/
protected $error_code = 0;
/**
* @var $error_msg 錯誤資訊
*/
protected $error_msg = '';
/**
* @var $file_ext 檔案擴展名
*/
protected $file_ext = '';
/**
* @var $type 檔案型別,默認為任意型別
*/
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;
}
/**
* 進行檔案上傳操作
*
* @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;
}
// 判斷檔案夾是否存在,如果不存在,新建一個檔案夾
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;
}
// 檔案未上傳成功,出現未知錯誤
$this->error_code = -1;
return false;
}
/**
* 回傳錯誤碼
*
* @return integer
*/
public function errorCode()
{
return $this->error_code;
}
/**
* 回傳錯誤資訊
*
* @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];
}
/**
* 判斷是否上傳錯誤
*
* @return boolean
*/
protected function uploadError()
{
$this->error_code = $this->file['error'];
return (bool)$this->file['error'];
}
/**
* 根據錯誤代碼設定錯誤資訊
*
* @param int $code
*/
protected function setErrorMsgByCode($code)
{
$msg_arr = [
'',
'上傳檔案最大為 ' . $this->getMaxSize() . 'M',
'上傳檔案過大',
'檔案只有部分被上傳',
'沒有檔案被上傳',
'檔案已存在',
'檔案丟失',
'檔案寫入失敗',
'只能上傳' . implode(',', $this->exts) . '型別的檔案'
];
$this->error_msg = $msg_arr[$code] ?? '未知錯誤';
}
/**
* 獲取上傳檔案所限制的最大大小
*
* @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;
}
/**
* 通過型別獲取后綴名陣列
*
* @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';
- 實體化類
$uploader = new E\FileUpload();
- 配置
$uploader->config([
'name' => 'file',
'exts' => ['jpg'],
'type' => 'image',
'max_size' => 2,
]);
配置項的說明:
| 配置項 | 說明 |
|---|---|
| name | 是 HTML 中 input 的 name,例如: <input type="file" name="file">,默認是 file |
| exts | 所允許上傳的檔案擴展名,型別為陣列,默認是任何型別的檔案 |
| type | 上傳檔案型別,可以通過設定 type 屬性,設定允許上傳型別,默認為 file,目前可選型別有:file 全部檔案型別,image 圖片型別, zip 壓縮包,注意:exts優先級高于 type,即如果設定了 type 為 file,exts 為 ['jpg'] 時,也還是只能上傳 jpg 型別的檔案的 |
| max_size | 所允許上傳的大小,單位為 M,默認為 2M |
- 上傳
$uploader->upload();
- 保存
$uploader->save('./uploads/', 'test')
save 方法的回傳值是一個布林值,上傳成功回傳 true,失敗回傳 false,可以根據回傳的狀態進行相應的操作,如果失敗,可以使用 errorCode() 方法獲取錯誤代碼,使用 errorMsg() 方法獲取錯誤資訊,
save 方法的第一個引數為必填引數,是要保存的路徑,第二個引數是檔案名,可選,如果不填,則會自動生成,生成規則: e_ 連接上當前時間的時間戳再連接5位亂數
也可以使用鏈式操作:
$uploader->upload()->save('./uploads/', 'test');
錯誤碼說明
| 錯誤碼 | 說明 |
|---|---|
| 0 | 無錯誤 |
| 1 | 上傳檔案超出限制大小 |
| 2 | 上傳檔案超出 form 表單所設定的 MAX_FILE_SIZE,也是檔案過大 |
| 3 | 檔案只有部分被上傳 |
| 4 | 沒有檔案被上傳 |
| 5 | 存在同名檔案 |
| 6 | 檔案丟失 |
| 7 | 檔案寫入失敗 |
| 8 | 上傳的檔案型別不被允許 |
| -1 | 未知錯誤 |
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/47260.html
標籤:PHP
