Upload.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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\store\controller;
  13. use app\store\model\Setting as SettingModel;
  14. use app\store\model\UploadFile as UploadFileModel;
  15. use app\common\enum\Setting as SettingEnum;
  16. use app\common\enum\file\FileType as FileTypeEnum;
  17. use app\common\library\storage\Driver as StorageDriver;
  18. /**
  19. * 文件库管理
  20. * Class Upload
  21. * @package app\store\controller
  22. */
  23. class Upload extends Controller
  24. {
  25. // 当前商城的上传设置
  26. private $config;
  27. /**
  28. * 构造方法
  29. * @throws \app\common\exception\BaseException
  30. * @throws \think\db\exception\DataNotFoundException
  31. * @throws \think\db\exception\DbException
  32. * @throws \think\db\exception\ModelNotFoundException
  33. */
  34. public function initialize()
  35. {
  36. parent::initialize();
  37. // 存储配置信息
  38. $this->config = SettingModel::getItem(SettingEnum::STORAGE);
  39. }
  40. /**
  41. * 图片上传接口
  42. * @param int $groupId 分组ID
  43. * @return array
  44. * @throws \think\Exception
  45. */
  46. public function image(int $groupId = 0)
  47. {
  48. // 实例化存储驱动
  49. $storage = new StorageDriver($this->config);
  50. // 设置上传文件的信息
  51. $storage->setUploadFile('iFile')
  52. ->setRootDirName((string)$this->getStoreId())
  53. ->setValidationScene('image')
  54. ->upload();
  55. // 执行文件上传
  56. if (!$storage->upload()) {
  57. return $this->renderError('图片上传失败:' . $storage->getError());
  58. }
  59. // 文件信息
  60. $fileInfo = $storage->getSaveFileInfo();
  61. // 添加文件库记录
  62. $model = new UploadFileModel;
  63. $model->add($fileInfo, FileTypeEnum::IMAGE, $groupId);
  64. // 图片上传成功
  65. return $this->renderSuccess(['fileInfo' => $model->toArray()], '图片上传成功');
  66. }
  67. }