Просмотр исходного кода

优化后台文件上传接口

萤火科技 3 лет назад
Родитель
Сommit
5a1bdfb55c

+ 8 - 3
app/common/library/Download.php

@@ -12,8 +12,13 @@ declare (strict_types=1);
 
 namespace app\common\library;
 
-use app\common\exception\BaseException;
+use cores\exception\BaseException;
 
+/**
+ * 文件下载类
+ * Class Download
+ * @package app\common\library
+ */
 class Download
 {
     /**
@@ -22,7 +27,7 @@ class Download
      * @param string $url
      * @param string $prefix
      * @return string
-     * @throws \cores\exception\BaseException
+     * @throws BaseException
      */
     public function saveTempImage(int $storeId, string $url, string $prefix = 'temp'): string
     {
@@ -72,7 +77,7 @@ class Download
     private function getSavePath(int $storeId, string $prefix, string $url): string
     {
         $dirPath = $this->getDirPath($storeId);
-        return $dirPath . '/' . $prefix . '_' . md5($url) . '.png';
+        return "{$dirPath}/{$prefix}_" . md5($url) . ".png";
     }
 
     /**

+ 18 - 52
app/store/controller/Upload.php

@@ -12,12 +12,9 @@ declare (strict_types=1);
 
 namespace app\store\controller;
 
-use app\store\model\Setting as SettingModel;
-use app\store\model\UploadFile as UploadFileModel;
-use app\common\enum\Setting as SettingEnum;
-use app\common\enum\file\FileType as FileTypeEnum;
-use app\common\library\storage\Driver as StorageDriver;
 use think\response\Json;
+use app\store\service\Upload as UploadService;
+use app\common\enum\file\FileType as FileTypeEnum;
 
 /**
  * 文件库管理
@@ -26,74 +23,43 @@ use think\response\Json;
  */
 class Upload extends Controller
 {
-    // 当前商城的上传设置
-    private $config;
-
-    /**
-     * 构造方法
-     * @throws \app\common\exception\BaseException
-     * @throws \think\db\exception\DataNotFoundException
-     * @throws \think\db\exception\DbException
-     * @throws \think\db\exception\ModelNotFoundException
-     */
-    public function initialize()
-    {
-        parent::initialize();
-        // 存储配置信息
-        $this->config = SettingModel::getItem(SettingEnum::STORAGE);
-    }
-
     /**
      * 图片上传接口
-     * @param int $groupId 分组ID
+     * @param int $groupId 文件库分组ID
      * @return Json
      * @throws \think\Exception
+     * @throws \think\db\exception\DataNotFoundException
+     * @throws \think\db\exception\DbException
+     * @throws \think\db\exception\ModelNotFoundException
      */
     public function image(int $groupId = 0): Json
     {
-        // 实例化存储驱动
-        $storage = new StorageDriver($this->config);
-        // 设置上传文件的信息
-        $storage->setUploadFile('iFile')
-            ->setRootDirName((string)$this->storeId)
-            ->setValidationScene('image');
         // 执行文件上传
-        if (!$storage->upload()) {
-            return $this->renderError('图片上传失败:' . $storage->getError());
+        $service = new UploadService();
+        if (!$service->upload(FileTypeEnum::IMAGE, $groupId)) {
+            return $this->renderError('文件上传失败:' . $service->getError());
         }
-        // 文件信息
-        $fileInfo = $storage->getSaveFileInfo();
-        // 添加文件库记录
-        $model = new UploadFileModel;
-        $model->add($fileInfo, FileTypeEnum::IMAGE, $groupId);
         // 图片上传成功
-        return $this->renderSuccess(['fileInfo' => $model->toArray()], '图片上传成功');
+        return $this->renderSuccess(['fileInfo' => $service->getFileInfo()], '文件上传成功');
     }
 
     /**
      * 视频上传接口
-     * @param int $groupId 分组ID
+     * @param int $groupId 文件库分组ID
      * @return Json
      * @throws \think\Exception
+     * @throws \think\db\exception\DataNotFoundException
+     * @throws \think\db\exception\DbException
+     * @throws \think\db\exception\ModelNotFoundException
      */
     public function video(int $groupId = 0): Json
     {
-        // 实例化存储驱动
-        $storage = new StorageDriver($this->config);
-        // 设置上传文件的信息
-        $storage->setUploadFile('iFile')
-            ->setRootDirName((string)$this->storeId)
-            ->setValidationScene('video');
         // 执行文件上传
-        if (!$storage->upload()) {
-            return $this->renderError('视频上传失败:' . $storage->getError());
+        $service = new UploadService();
+        if (!$service->upload(FileTypeEnum::VIDEO, $groupId)) {
+            return $this->renderError('文件上传失败:' . $service->getError());
         }
-        // 文件信息
-        $fileInfo = $storage->getSaveFileInfo();
-        // 添加文件库记录
-        $model = new UploadFileModel;
-        $model->add($fileInfo, FileTypeEnum::VIDEO, $groupId);
         // 图片上传成功
-        return $this->renderSuccess(['fileInfo' => $model->toArray()], '视频上传成功');
+        return $this->renderSuccess(['fileInfo' => $service->getFileInfo()], '文件上传成功');
     }
 }

+ 6 - 6
app/store/model/Goods.php

@@ -21,7 +21,7 @@ use app\store\model\GoodsSpecRel as GoodsSpecRelModel;
 use app\store\model\goods\ServiceRel as GoodsServiceRelModel;
 use app\store\model\GoodsCategoryRel as GoodsCategoryRelModel;
 use app\store\service\Goods as GoodsService;
-use app\common\enum\goods\SpecType as SpecTypeEnum;
+use app\common\enum\goods\SpecType as GoodsSpecTypeEnum;
 use app\common\enum\goods\Status as GoodsStatusEnum;
 use cores\exception\BaseException;
 
@@ -48,7 +48,7 @@ class Goods extends GoodsModel
         // 分类ID集
         $goodsInfo['categoryIds'] = GoodsCategoryRelModel::getCategoryIds($goodsInfo['goods_id']);
         // 商品多规格属性列表
-        if ($goodsInfo['spec_type'] == SpecTypeEnum::MULTI) {
+        if ($goodsInfo['spec_type'] == GoodsSpecTypeEnum::MULTI) {
             $goodsInfo['specList'] = GoodsSpecRelModel::getSpecList($goodsInfo['goods_id']);
         }
         // 服务与承诺
@@ -208,24 +208,24 @@ class Goods extends GoodsModel
         ]);
         // 库存总量 stock_total
         // 商品价格 最低最高
-        if ($data['spec_type'] == SpecTypeEnum::MULTI) {
+        if ($data['spec_type'] == GoodsSpecTypeEnum::MULTI) {
             $data['stock_total'] = GoodsSkuModel::getStockTotal($data['specData']['skuList']);
             [$data['goods_price_min'], $data['goods_price_max']] = GoodsSkuModel::getGoodsPrices($data['specData']['skuList']);
             [$data['line_price_min'], $data['line_price_max']] = GoodsSkuModel::getLinePrices($data['specData']['skuList']);
-        } elseif ($data['spec_type'] == SpecTypeEnum::SINGLE) {
+        } elseif ($data['spec_type'] == GoodsSpecTypeEnum::SINGLE) {
             $data['goods_price_min'] = $data['goods_price_max'] = $data['goods_price'];
             $data['line_price_min'] = $data['line_price_max'] = $data['line_price'];
             $data['stock_total'] = $data['stock_num'];
         }
         // 规格和sku数据处理
-        if ($data['spec_type'] == SpecTypeEnum::MULTI) {
+        if ($data['spec_type'] == GoodsSpecTypeEnum::MULTI) {
             // 验证规格值是否合法
             SpecModel::checkSpecData($data['specData']['specList']);
             // 生成多规格数据 (携带id)
             $data['newSpecList'] = SpecModel::getNewSpecList($data['specData']['specList']);
             // 生成skuList (携带goods_sku_id)
             $data['newSkuList'] = GoodsSkuModel::getNewSkuList($data['newSpecList'], $data['specData']['skuList']);
-        } elseif ($data['spec_type'] == SpecTypeEnum::SINGLE) {
+        } elseif ($data['spec_type'] == GoodsSpecTypeEnum::SINGLE) {
             // 生成skuItem
             $data['newSkuList'] = helper::pick($data, ['goods_price', 'line_price', 'stock_num', 'goods_weight']);
         }

+ 112 - 0
app/store/service/Upload.php

@@ -0,0 +1,112 @@
+<?php
+// +----------------------------------------------------------------------
+// | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
+// +----------------------------------------------------------------------
+// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
+// +----------------------------------------------------------------------
+// | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
+// +----------------------------------------------------------------------
+// | Author: 萤火科技 <admin@yiovo.com>
+// +----------------------------------------------------------------------
+declare (strict_types=1);
+
+namespace app\store\service;
+
+use app\store\model\Setting as SettingModel;
+use app\store\model\UploadFile as UploadFileModel;
+use app\common\enum\Setting as SettingEnum;
+use app\common\enum\file\FileType as FileTypeEnum;
+use app\common\library\storage\Driver as StorageDriver;
+use app\common\service\BaseService;
+
+/**
+ * 文件上传服务类
+ * Class Upload
+ * @package app\store\service
+ */
+class Upload extends BaseService
+{
+    /**
+     * 文件上传场景
+     */
+    const UPLOAD_SCENE_ENUM = [
+        FileTypeEnum::IMAGE => 'image',
+        FileTypeEnum::VIDEO => 'video',
+    ];
+
+    /**
+     * 上传成功的文件信息
+     * @var array
+     */
+    private array $fileInfo = [];
+
+    /**
+     * 图片上传接口
+     * @param int $fileType 文件类型 image和video
+     * @param int $groupId 分组ID
+     * @return bool
+     * @throws \think\Exception
+     * @throws \think\db\exception\DataNotFoundException
+     * @throws \think\db\exception\DbException
+     * @throws \think\db\exception\ModelNotFoundException
+     */
+    public function upload(int $fileType, int $groupId = 0): bool
+    {
+        // 实例化上传驱动
+        $storage = $this->getStorage(self::UPLOAD_SCENE_ENUM[$fileType]);
+        // 执行文件上传
+        if (!$storage->upload()) {
+            $this->error = $storage->getError();
+            return false;
+        }
+        // 文件信息
+        $fileInfo = $storage->getSaveFileInfo();
+        // 添加文件库记录
+        $model = new UploadFileModel;
+        $model->add($fileInfo, $fileType, $groupId);
+        $this->fileInfo = $model->toArray();
+        return true;
+    }
+
+    /**
+     * 上传成功的文件信息
+     * @return array
+     */
+    public function getFileInfo(): array
+    {
+        return $this->fileInfo;
+    }
+
+    /**
+     * 实例化上传驱动
+     * @param string $scene 上传场景 image和video
+     * @return mixed
+     * @throws \think\Exception
+     * @throws \think\db\exception\DataNotFoundException
+     * @throws \think\db\exception\DbException
+     * @throws \think\db\exception\ModelNotFoundException
+     */
+    private function getStorage(string $scene)
+    {
+        // 获取文件上传设置
+        $config = $this->getConfig();
+        // 实例化存储驱动
+        $storage = new StorageDriver($config);
+        // 设置上传文件的信息
+        return $storage->setUploadFile('iFile')
+            ->setRootDirName((string)$this->getStoreId())
+            ->setValidationScene($scene);
+    }
+
+    /**
+     * 获取文件上传设置
+     * @return array|mixed
+     * @throws \think\db\exception\DataNotFoundException
+     * @throws \think\db\exception\DbException
+     * @throws \think\db\exception\ModelNotFoundException
+     */
+    private function getConfig()
+    {
+        return SettingModel::getItem(SettingEnum::STORAGE);
+    }
+}