Upload.php 2.5 KB

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