UploadForm.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. /**
  3. * 重庆赤晓店信息科技有限公司
  4. * https://www.chixiaodian.com
  5. * Copyright (c) 2023 赤店商城 All rights reserved.
  6. */
  7. namespace app\modules\client\models\v1;
  8. use app\models\Storage;
  9. use yii\base\Model;
  10. use app\modules\admin\models\StorageForm;
  11. use app\models\common\Upload;
  12. use Yii;
  13. class UploadForm extends Model
  14. {
  15. public $store_id;
  16. /**
  17. * 上传文件
  18. * @param string $name
  19. * @param string $type
  20. * @return array
  21. */
  22. public function uploadFile($name = 'file', $type = 'image')
  23. {
  24. try {
  25. $file = Yii::$app->storage->getUploadedFile($name);
  26. $maxUploadSize = Upload::getMaxUploadSize();
  27. $uploadSize = $maxUploadSize * 1024 * 1024;
  28. // 检查mime和扩展名
  29. if (false === $this->checkMime($file->getExtension(), $file->type, $type)) {
  30. throw new \Exception('文件格式不正确');
  31. }
  32. // 检查文件大小
  33. if ($file->size > $uploadSize) {
  34. throw new \Exception('上传文件不能超过 ' . $maxUploadSize . 'M');
  35. }
  36. $uniqueName = sha1_file($file->tempName);
  37. $saveDir = $this->getUploadDir($uniqueName, $type);
  38. $url = $file->saveWithOriginalExtension($saveDir);
  39. return [
  40. 'code' => 0,
  41. 'msg' => 'success',
  42. 'data' => [
  43. 'url' => $url,
  44. 'extension' => $file->getExtension(),
  45. 'size' => $file->size,
  46. 'type' => $type,
  47. ],
  48. ];
  49. } catch (\Throwable $throwable) {
  50. return [
  51. 'code' => 1,
  52. 'msg' => $throwable->getMessage(),
  53. ];
  54. }
  55. }
  56. /**
  57. * 获取上传目录
  58. * @param $name
  59. * @param string $type
  60. * @return string
  61. */
  62. private function getUploadDir($name, $type = 'image')
  63. {
  64. $timeDir = date('Y-m-d');
  65. $typeDir = $type === 'image' ? 'images' : 'videos';
  66. return sprintf('%s/store_%d/user/%s/%s', $typeDir, $this->store_id, $timeDir, $name);
  67. }
  68. /**
  69. * 检测扩展名和mime
  70. * @param $ext
  71. * @param $mime
  72. * @param string $type
  73. * @return bool
  74. */
  75. private function checkMime($ext, $mime, $type = 'image')
  76. {
  77. $extType = Storage::IMAGE_TYPE;
  78. $mimeType = Storage::IMAGE_MIME;
  79. if ($type == 'video') {
  80. $extType = Storage::VIDEO_TYPE;
  81. $mimeType = Storage::VIDEO_MIME;
  82. }
  83. if (in_array($ext, $extType) && in_array($mime, $mimeType)) {
  84. return true;
  85. }
  86. return false;
  87. }
  88. }