1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 |
- <?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('未上传文件');
- }
- $uploadPath = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'temp';
- if (!is_dir($uploadPath)) {
- @mkdir($uploadPath, 0755, true);
- }
- $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());
- }
- }
- }
|