Files
code-bang/backend/application/common/library/OssUpload.php
T

103 lines
3.6 KiB
PHP
Raw Normal View History

2026-10-14 16:26:41 +08:00
<?php
namespace app\common\library;
use app\common\exception\UploadException;
use app\common\model\Attachment;
use app\common\service\OssService;
use fast\Random;
use think\File;
use think\Hook;
/**
* OSS 文件上传
* 本地只落地到 runtime/temp(PHP 运行用户可写,不依赖 public/uploads 的写权限),
* 上传到 OSS 后删除临时文件,附件记录保存 OSS 路径
*/
class OssUpload extends Upload
{
/**
* 上传到 OSS(普通上传与分片合并共用)
* @param string|null $savekey 未使用,OSS 路径固定为 uploads/{Ymd}/{随机串}/{原文件名}
* @return \app\common\model\attachment|\think\Model
* @throws UploadException
*/
public function upload($savekey = null)
{
if (empty($this->file)) {
throw new UploadException(__('No file upload or server upload limit exceeded'));
}
$this->checkSize();
$this->checkExecutable();
$this->checkMimetype();
$this->checkImage();
$tempDir = RUNTIME_PATH . 'temp' . DS;
if (!is_dir($tempDir) && !@mkdir($tempDir, 0775, true) && !is_dir($tempDir)) {
throw new UploadException('上传临时目录创建失败或无写权限:' . $tempDir);
}
$tempName = Random::alnum(16) . '.' . $this->fileInfo['suffix'];
$tempFile = $tempDir . $tempName;
$sha1 = $this->file->hash();
if ($this->merging) {
if (!$this->file->check()) {
throw new UploadException($this->file->getError());
}
$sourceFile = $this->file->getRealPath() ?: $this->file->getPathname();
$info = $this->file->getInfo();
$this->file = null;
if (!@rename($sourceFile, $tempFile)) {
throw new UploadException('分片文件合并失败');
}
$file = new File($tempFile);
$file->setSaveName($tempName)->setUploadInfo($info);
} else {
$file = $this->file->move($tempDir, $tempName);
if (!$file) {
throw new UploadException($this->file->getError());
}
}
$this->file = $file;
$filename = mb_substr(htmlspecialchars(strip_tags($this->fileInfo['name'])), 0, 100);
$object = 'uploads/' . date('Ymd/') . Random::alnum(16) . '/' . $filename;
try {
OssService::instance()->uploadFile($tempFile, $object);
} catch (\Exception $e) {
throw new UploadException($e->getMessage());
} finally {
@unlink($tempFile);
}
$category = request()->post('category');
$category = array_key_exists($category, config('site.attachmentcategory') ?? []) ? $category : '';
$auth = Auth::instance();
$params = [
'admin_id' => (int)session('admin.id'),
'user_id' => (int)$auth->id,
'filename' => $filename,
'category' => $category,
'filesize' => $this->fileInfo['size'],
'imagewidth' => $this->fileInfo['imagewidth'],
'imageheight' => $this->fileInfo['imageheight'],
'imagetype' => $this->fileInfo['suffix'],
'imageframes' => 0,
'mimetype' => $this->fileInfo['type'],
'url' => '/' . $object,
'uploadtime' => time(),
'storage' => 'oss',
'sha1' => $sha1,
'extparam' => '',
];
$attachment = new Attachment();
$attachment->data(array_filter($params));
$attachment->save();
Hook::listen('upload_after', $attachment);
return $attachment;
}
}