TP6.0内置文件上传只是上传到本地服务器,上传到远程或者第三方平台的话需要安装额外的扩展,本文章对基于TP6.0的内置文件上传进行封装。
个人技术博客:https://www.itqaq.com
1. 使用方法
简单示例
Upload
::putFile('磁盘', '文件字段域', '目录名');
Upload
::putFile('public', 'img');
Upload
::putFile('public', 'img', 'thumb');
上传成功和 上传失败 时的返回值
2. 文件上传封装类
<?php
use think\facade\Config;
use think\facade\Filesystem;
use think\exception\ValidateException;
class Upload
{
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)
{
return array_filter(compact('result', 'msg', 'path'), function($v){
return !is_null($v);
});
}
}