Upload.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. namespace app\api\controller;
  3. use app\common\controller\Api;
  4. use app\common\service\OssService;
  5. use think\Exception;
  6. use think\File;
  7. use Fast\Random;
  8. class Upload extends Api
  9. {
  10. protected $noNeedLogin = ['*'];
  11. protected $noNeedRight = ['*'];
  12. /**
  13. * 文件上传
  14. *
  15. * @ApiMethod (POST)
  16. */
  17. public function upload()
  18. {
  19. try {
  20. // if (!$this->auth->isLogin()) {
  21. // $this->error('请先登录');
  22. // }
  23. $files = $this->request->file();
  24. if (empty($files)) {
  25. $this->error('未上传文件');
  26. }
  27. $uploadPath = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'temp';
  28. if (!is_dir($uploadPath)) {
  29. @mkdir($uploadPath, 0755, true);
  30. }
  31. $urls = [];
  32. $ossService = OssService::instance();
  33. foreach ($files as $file) {
  34. $info = $file->validate(['size' => 50 * 1024 * 1024, 'ext' => 'jpg,jpeg,png,gif,doc,docx,pdf,xls,xlsx'])->rule('uniqid')->move($uploadPath);
  35. if (!$info) {
  36. throw new Exception($file->getError());
  37. }
  38. $filePath = $uploadPath . DS . $info->getSaveName();
  39. $fileName = mb_substr(htmlspecialchars(strip_tags($this->request->post('name'))), 0, 130);
  40. $object = 'uploads/' . date('Ymd/') . Random::alnum(16) . '/' . $fileName;
  41. // 上传到OSS
  42. $url = $ossService->uploadFile($filePath, $object);
  43. $urls[] = [
  44. 'url' => $url,
  45. 'filePath' => $filePath,
  46. 'name' => $fileName,
  47. 'size' => $info->getSize(),
  48. 'mime_type' => $info->getMime()
  49. ];
  50. // 删除临时文件
  51. @unlink($filePath);
  52. }
  53. $this->success('上传成功', $urls);
  54. } catch (Exception $e) {
  55. $this->error($e->getMessage());
  56. }
  57. }
  58. }