Upload.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2017~2021 https://www.yiovo.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
  8. // +----------------------------------------------------------------------
  9. // | Author: 萤火科技 <admin@yiovo.com>
  10. // +----------------------------------------------------------------------
  11. declare (strict_types=1);
  12. namespace app\api\controller;
  13. use app\api\model\Setting as SettingModel;
  14. use app\api\model\UploadFile as UploadFileModel;
  15. use app\api\service\User as UserService;
  16. use app\common\enum\Setting as SettingEnum;
  17. use app\common\enum\file\FileType as FileTypeEnum;
  18. use app\common\library\storage\Driver as StorageDriver;
  19. use app\common\exception\BaseException;
  20. /**
  21. * 文件库管理
  22. * Class Upload
  23. * @package app\api\controller
  24. */
  25. class Upload extends Controller
  26. {
  27. // 当前商城的上传设置
  28. private $config;
  29. /**
  30. * 构造方法
  31. * @throws BaseException
  32. * @throws \think\db\exception\DataNotFoundException
  33. * @throws \think\db\exception\DbException
  34. * @throws \think\db\exception\ModelNotFoundException
  35. */
  36. public function initialize()
  37. {
  38. parent::initialize();
  39. // 验证登录
  40. UserService::isLogin(true);
  41. // 存储配置信息
  42. $this->config = SettingModel::getItem(SettingEnum::STORAGE);
  43. }
  44. /**
  45. * 图片上传接口
  46. * @return array|\think\response\Json
  47. * @throws BaseException
  48. * @throws \think\Exception
  49. */
  50. public function image()
  51. {
  52. // 当前用户ID
  53. $userId = UserService::getCurrentLoginUserId();
  54. // 实例化存储驱动
  55. $storage = new StorageDriver($this->config);
  56. // 设置上传文件的信息
  57. $storage->setUploadFile('file')
  58. ->setRootDirName((string)$this->getStoreId())
  59. ->setValidationScene('image')
  60. ->upload();
  61. // 执行文件上传
  62. if (!$storage->upload()) {
  63. return $this->renderError('图片上传失败:' . $storage->getError());
  64. }
  65. // 文件信息
  66. $fileInfo = $storage->getSaveFileInfo();
  67. // 添加文件库记录
  68. $model = new UploadFileModel;
  69. $model->add($fileInfo, FileTypeEnum::IMAGE, $userId);
  70. // 图片上传成功
  71. return $this->renderSuccess(['fileInfo' => $model->toArray()], '图片上传成功');
  72. }
  73. }