Upload.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. /**
  3. *
  4. * @copyright ©2020 点小铺
  5. * @author hanj
  6. * @link: https://dyuit.com
  7. * Created by VSCode
  8. */
  9. namespace app\store\controller;
  10. use app\store\model\UploadFile;
  11. use app\common\library\storage\Driver as StorageDriver;
  12. use app\store\model\Setting as SettingModel;
  13. /**
  14. * 文件库管理
  15. * Class Upload
  16. * @package app\store\controller
  17. */
  18. class Upload extends Controller
  19. {
  20. private $config;
  21. /**
  22. * 构造方法
  23. * @throws \app\common\exception\BaseException
  24. * @throws \think\db\exception\DataNotFoundException
  25. * @throws \think\db\exception\ModelNotFoundException
  26. * @throws \think\exception\DbException
  27. */
  28. public function _initialize()
  29. {
  30. parent::_initialize();
  31. // 存储配置信息
  32. $this->config = SettingModel::getItem('storage');
  33. }
  34. /**
  35. * 图片上传接口
  36. * @param int $group_id
  37. * @return array
  38. * @throws \think\Exception
  39. */
  40. public function image($group_id = -1)
  41. {
  42. // 实例化存储驱动
  43. $StorageDriver = new StorageDriver($this->config);
  44. // 设置上传文件的信息
  45. $StorageDriver->setUploadFile('iFile');
  46. // 上传图片
  47. if (!$StorageDriver->upload()) {
  48. return json(['code' => 0, 'msg' => '图片上传失败' . $StorageDriver->getError()]);
  49. }
  50. // 图片上传路径
  51. $fileName = $StorageDriver->getFileName();
  52. // 图片信息
  53. $fileInfo = $StorageDriver->getFileInfo();
  54. // 添加文件库记录
  55. $uploadFile = $this->addUploadFile($group_id, $fileName, $fileInfo, 'image');
  56. // 图片上传成功
  57. return json(['code' => 1, 'msg' => '图片上传成功', 'data' => $uploadFile]);
  58. }
  59. /**
  60. * 添加文件库上传记录
  61. * @param $group_id
  62. * @param $fileName
  63. * @param $fileInfo
  64. * @param $fileType
  65. * @return UploadFile
  66. */
  67. private function addUploadFile($group_id, $fileName, $fileInfo, $fileType)
  68. {
  69. // 存储引擎
  70. $storage = $this->config['default'];
  71. // 存储域名
  72. $fileUrl = isset($this->config['engine'][$storage]['domain'])
  73. ? $this->config['engine'][$storage]['domain'] : '';
  74. // 添加文件库记录
  75. $model = new UploadFile;
  76. $model->add([
  77. 'group_id' => $group_id > 0 ? (int)$group_id : 0,
  78. 'storage' => $storage,
  79. 'file_url' => $fileUrl,
  80. 'file_name' => $fileName,
  81. 'file_size' => $fileInfo['size'],
  82. 'file_type' => $fileType,
  83. 'extension' => pathinfo($fileInfo['name'], PATHINFO_EXTENSION),
  84. ]);
  85. return $model;
  86. }
  87. }