69 lines
2.2 KiB
PHP
69 lines
2.2 KiB
PHP
<?php
|
|
|
|
namespace app\api\controller;
|
|
|
|
use app\common\controller\Api;
|
|
use app\common\service\OssService;
|
|
use think\Exception;
|
|
use think\File;
|
|
use fast\Random;
|
|
|
|
class Upload extends Api
|
|
{
|
|
protected $noNeedLogin = ['*'];
|
|
protected $noNeedRight = ['*'];
|
|
|
|
/**
|
|
* 文件上传
|
|
*
|
|
* @ApiMethod (POST)
|
|
*/
|
|
public function upload()
|
|
{
|
|
try {
|
|
// if (!$this->auth->isLogin()) {
|
|
// $this->error('请先登录');
|
|
// }
|
|
|
|
$files = $this->request->file();
|
|
if (empty($files)) {
|
|
$this->error('未上传文件');
|
|
}
|
|
// 临时目录使用 runtime(位于 web 根目录之外,且已对 PHP 运行用户开放写权限)
|
|
$uploadPath = RUNTIME_PATH . 'temp';
|
|
if (!is_dir($uploadPath) && !@mkdir($uploadPath, 0775, true) && !is_dir($uploadPath)) {
|
|
throw new Exception('上传临时目录创建失败或无写权限:' . $uploadPath);
|
|
}
|
|
|
|
$urls = [];
|
|
$ossService = OssService::instance();
|
|
foreach ($files as $file) {
|
|
$info = $file->validate(['size' => 50 * 1024 * 1024, 'ext' => 'jpg,jpeg,png,gif,doc,docx,pdf,xls,xlsx'])->rule('uniqid')->move($uploadPath);
|
|
|
|
if (!$info) {
|
|
throw new Exception($file->getError());
|
|
}
|
|
$filePath = $uploadPath . DS . $info->getSaveName();
|
|
$fileName = mb_substr(htmlspecialchars(strip_tags($this->request->post('name'))), 0, 130);
|
|
$object = 'uploads/' . date('Ymd/') . Random::alnum(16) . '/' . $fileName;
|
|
|
|
// 上传到OSS
|
|
$url = $ossService->uploadFile($filePath, $object);
|
|
$urls[] = [
|
|
'url' => $url,
|
|
'filePath' => $filePath,
|
|
'name' => $fileName,
|
|
'size' => $info->getSize(),
|
|
'mime_type' => $info->getMime()
|
|
];
|
|
|
|
// 删除临时文件
|
|
@unlink($filePath);
|
|
}
|
|
|
|
$this->success('上传成功', $urls);
|
|
} catch (Exception $e) {
|
|
$this->error($e->getMessage());
|
|
}
|
|
}
|
|
}
|