> TP 內置的文件上傳(文件上傳到服務器)
#### 1\. 使用方法
* * *
**簡單示例**
~~~
// 返回數組
Upload::putFile('磁盤', '文件字段域', '目錄名');
~~~
~~~
Upload::putFile('public', 'img');
Upload::putFile('public', 'img', 'thumb');
~~~
**`上傳成功`和`上傳失敗`時的返回值**


#### 2\. 文件上傳封裝類
* * *
~~~
<?php
// 本文件放在TP6.0.*的extend目錄下
// extend/Upload.php
use think\facade\Config;
use think\facade\Filesystem;
use think\exception\ValidateException;
/**
* 文件上傳封裝
* @author liang
* @datetime 2020-07-01
*/
class Upload
{
/**
* 執行文件上傳
* @param string $disks 磁盤名稱
* @param string $field 字段名
* @param string $dir 文件存放目錄名,默認和字段名相同
* @return array 文件上傳結果數組
*/
public static function putFile(string $disks = '', string $field = '', string $dir = '')
{
// 此時也可能報錯
// 比如上傳的文件過大,超出了配置文件中限制的大小
try {
$file = request()->file($field);
} catch (\think\Exception $e) {
return self::_rtnData(false, self::_languageChange($e->getMessage()));
}
// 確定使用的磁盤
$disks = $disks ?: Filesystem::getDefaultDriver();
// 文件存放目錄名稱
$dirname = $dir ?: $field;
// 從存放目錄開始的存放路徑
$savename = Filesystem::disk($disks)->putFile($dirname, $file);
// 完整路徑
$path = Filesystem::getDiskConfig($disks, 'url') . '/' . str_replace('\\', '/', $savename);
// 返回上傳成功時的數組
return self::_rtnData(true, '上傳成功', $path);
}
/**
* 英文轉為中文
*/
private static function _languageChange($msg)
{
$data = [
// 上傳錯誤信息
'unknown upload error' => '未知上傳錯誤!',
'file write error' => '文件寫入失敗!',
'upload temp dir not found' => '找不到臨時文件夾!',
'no file to uploaded' => '沒有文件被上傳!',
'only the portion of file is uploaded' => '文件只有部分被上傳!',
'upload File size exceeds the maximum value' => '上傳文件大小超過了最大值!',
'upload write error' => '文件上傳保存錯誤!',
];
return $data[$msg] ?? $msg;
}
/**
* 文件上傳返回結果數組
*/
private static function _rtnData(bool $result, $msg = null, $path = null)
{
// 過濾掉值為null的數組元素
return array_filter(compact('result', 'msg', 'path'), function($v){
return !is_null($v);
});
}
}
~~~
- 搭建ThinkPHP6的開發環境
- 配置ThinkPHP6
- 必要的基礎知識(basic)
- MVC開發模式
- 控制器(controller)
- 數據庫(database)
- 模型(model)
- 模型關聯(relation)
- 視圖(view)
- Session
- Cookie
- 緩存(cache)
- 上傳(upload)
- 驗證器(validate)
- 驗證碼(captcha)
- 命令行(command)
- 服務器部署(deploy)
- 數據備份(backup)
- 數據同步(synchronization)
- 訂閱服務(subscribe)
- PHP 易混淆知識點
- 助手函數
- MySQL規范
- Redis 規范
- office插件 phpoffice
- 拼音插件 pinyin
- 日期插件 datetime
- 消息插件 amqp
- 產品部署環境的搭建
- PDF 等雜項處理
- 文件上傳
- 常用擴展
- flc/dysms
- 使用示例 ①
- 使用示例 ②
- qiniu/php-sdk
- 簡介
- 使用示例
- 使用示例 2 ②
- liliuwei/thinkphp-jump
- 擴展介紹
- 下載擴展
- 使用方法
- topthink/think-captcha
- 安裝擴展
- 驗證碼顯示
- 更換驗證碼
- 驗證碼校驗
- 驗證碼配置
- 自定義驗證碼
- phpoffice/phpspreadsheet
- 數據寫入表格
- 讀取表格數據
- topthink/think-queue
- 安裝
- 自定義函數
- 任務類
- 帶有日志的任務類