| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- <?php
- /**
- * 重庆赤晓店信息科技有限公司
- * https://www.chixiaodian.com
- * Copyright (c) 2023 赤店商城 All rights reserved.
- */
- namespace app\modules\client\models\v1;
- use app\models\Storage;
- use yii\base\Model;
- use app\modules\admin\models\StorageForm;
- use app\models\common\Upload;
- use Yii;
- class UploadForm extends Model
- {
- public $store_id;
- /**
- * 上传文件
- * @param string $name
- * @param string $type
- * @return array
- */
- public function uploadFile($name = 'file', $type = 'image')
- {
- try {
- $file = Yii::$app->storage->getUploadedFile($name);
- $maxUploadSize = Upload::getMaxUploadSize();
- $uploadSize = $maxUploadSize * 1024 * 1024;
- // 检查mime和扩展名
- if (false === $this->checkMime($file->getExtension(), $file->type, $type)) {
- throw new \Exception('文件格式不正确');
- }
- // 检查文件大小
- if ($file->size > $uploadSize) {
- throw new \Exception('上传文件不能超过 ' . $maxUploadSize . 'M');
- }
- $uniqueName = sha1_file($file->tempName);
- $saveDir = $this->getUploadDir($uniqueName, $type);
- $url = $file->saveWithOriginalExtension($saveDir);
- return [
- 'code' => 0,
- 'msg' => 'success',
- 'data' => [
- 'url' => $url,
- 'extension' => $file->getExtension(),
- 'size' => $file->size,
- 'type' => $type,
- ],
- ];
- } catch (\Throwable $throwable) {
- return [
- 'code' => 1,
- 'msg' => $throwable->getMessage(),
- ];
- }
- }
- /**
- * 获取上传目录
- * @param $name
- * @param string $type
- * @return string
- */
- private function getUploadDir($name, $type = 'image')
- {
- $timeDir = date('Y-m-d');
- $typeDir = $type === 'image' ? 'images' : 'videos';
- return sprintf('%s/store_%d/user/%s/%s', $typeDir, $this->store_id, $timeDir, $name);
- }
- /**
- * 检测扩展名和mime
- * @param $ext
- * @param $mime
- * @param string $type
- * @return bool
- */
- private function checkMime($ext, $mime, $type = 'image')
- {
- $extType = Storage::IMAGE_TYPE;
- $mimeType = Storage::IMAGE_MIME;
- if ($type == 'video') {
- $extType = Storage::VIDEO_TYPE;
- $mimeType = Storage::VIDEO_MIME;
- }
- if (in_array($ext, $extType) && in_array($mime, $mimeType)) {
- return true;
- }
- return false;
- }
- }
|