UploadService.php 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. <?php
  2. namespace services\extend;
  3. use Yii;
  4. use common\helpers\Url;
  5. use yii\helpers\Json;
  6. use yii\web\UnprocessableEntityHttpException;
  7. use common\enums\StatusEnum;
  8. use common\forms\UploadForm;
  9. use common\helpers\UploadHelper;
  10. use common\components\Service;
  11. use common\helpers\ArrayHelper;
  12. use common\enums\AttachmentUploadTypeEnum;
  13. use common\enums\AttachmentDriveEnum;
  14. /**
  15. * Class UploadService
  16. * @package services\extend
  17. * @author jianyan74 <751393839@qq.com>
  18. */
  19. class UploadService extends Service
  20. {
  21. /**
  22. * @var UploadForm
  23. */
  24. protected $form;
  25. /**
  26. * 下载图片
  27. *
  28. * @param string $imageUrl
  29. * @param int $cycleIndex
  30. * @return array|UploadForm
  31. * @throws UnprocessableEntityHttpException
  32. */
  33. public function downloadByUrl(string $imageUrl, $cycleIndex = 0)
  34. {
  35. if (empty($imageUrl)) {
  36. return [];
  37. }
  38. try {
  39. // 下载图片
  40. $uploadForm = $this->saveFile([
  41. 'writeTable' => StatusEnum::DISABLED,
  42. 'fileData' => $imageUrl
  43. ], AttachmentUploadTypeEnum::IMAGES, 'url');
  44. $info = $uploadForm->getInfo();
  45. return $info;
  46. } catch (\Exception $e) {
  47. $cycleIndex++;
  48. if ($cycleIndex <= 3) {
  49. return $this->downloadByUrl($imageUrl, $cycleIndex);
  50. } else {
  51. throw new UnprocessableEntityHttpException('获取图片失败');
  52. }
  53. }
  54. }
  55. /**
  56. * 上传图片
  57. *
  58. * @param array $data
  59. * @param string $uploadType
  60. * @param string $fileSource
  61. * @return UploadForm
  62. * @throws UnprocessableEntityHttpException
  63. */
  64. public function saveFile(array $data, string $uploadType, string $fileSource = 'file')
  65. {
  66. $form = new UploadForm();
  67. $form->attributes = $data;
  68. $form->upload_type = $uploadType;
  69. $form->fileSource = $fileSource;
  70. $form->superAddition = true;
  71. $form->driveConfig = ArrayHelper::merge(Yii::$app->params['uploadConfig'][$uploadType], $data);
  72. empty($form->drive) && $form->drive = Yii::$app->services->config->backendConfig('storage_default');
  73. $form->pathInit();
  74. $form->fileSystemInit();
  75. // 判断是否切片上传
  76. if ($form->chunks > 0 && !empty($form->guid)) {
  77. $form->drive = AttachmentDriveEnum::LOCAL;
  78. $form->isCut = true;
  79. }
  80. if (!$form->validate()) {
  81. $this->error($form);
  82. }
  83. return UploadHelper::save($form);
  84. }
  85. /**
  86. * 获取阿里云js直传
  87. *
  88. * @param $maxSize
  89. * @param string dir 用户上传文件时指定的前缀
  90. * @param int $expire 设置该policy超时时间是10s. 即这个policy过了这个有效时间,将不能访问
  91. * @param string $callbackUrl 为上传回调服务器的URL,请将下面的IP和Port配置为您自己的真实URL信息
  92. * @return array
  93. * @throws \Exception
  94. */
  95. public function ossConfig(
  96. $maxSize,
  97. $path = '',
  98. $expire = 30,
  99. $type = AttachmentUploadTypeEnum::FILES,
  100. $callbackUrl = ''
  101. ) {
  102. $config = Yii::$app->services->config->configAll();
  103. $id = $config['storage_aliyun_accesskeyid'];
  104. $key = $config['storage_aliyun_accesskeysecret'];
  105. $bucket = $config['storage_aliyun_bucket'];
  106. $endpoint = $config['storage_aliyun_endpoint'];
  107. $host = "https://$bucket.$endpoint";
  108. // CNAME别名
  109. if (!empty($config['storage_aliyun_user_url'])) {
  110. $host = $config['storage_aliyun_transport_protocols'] . "://" . $config['storage_aliyun_user_url'];
  111. }
  112. $inAddon = Yii::$app->params['inAddon'];
  113. Yii::$app->params['inAddon'] = false;
  114. !$callbackUrl && $callbackUrl = Url::toApi(['v1/common/storage/oss'], true);
  115. Yii::$app->params['inAddon'] = $inAddon;
  116. $callback_param = [
  117. 'callbackUrl' => $callbackUrl,
  118. 'callbackBody' => 'filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}&format=${imageInfo.format}&md5=${x:md5}&merchant_id=${x:merchant_id}&type=${x:type}&host=${x:host}&ip=${x:ip}',
  119. 'callbackBodyType' => "application/x-www-form-urlencoded"
  120. ];
  121. $base64_callback_body = base64_encode(Json::encode($callback_param));
  122. $expiration = $this->expiration(time() + $expire);
  123. // 最大文件大小
  124. $conditions[] = ['content-length-range', 0, $maxSize];
  125. // 表示用户上传的数据,必须是以$dir开始,不然上传会失败,这一步不是必须项,只是为了安全起见,防止用户通过policy上传到别人的目录。
  126. // $conditions[] = ['starts-with','$filename', $dir];
  127. $arr = [
  128. 'expiration' => $expiration,
  129. 'conditions' => $conditions
  130. ];
  131. $policy = Json::encode($arr);
  132. $base64_policy = base64_encode($policy);
  133. $signature = base64_encode(hash_hmac('sha1', $base64_policy, $key, true));
  134. return [
  135. 'Filename' => '${filename}',
  136. 'key' => $path . '${filename}',
  137. 'OSSAccessKeyId' => $id,
  138. 'success_action_status' => '201',
  139. 'host' => $host,
  140. 'policy' => $base64_policy,
  141. 'signature' => $signature,
  142. 'callback' => $base64_callback_body,
  143. 'x:merchant_id' => Yii::$app->services->merchant->getNotNullId(),
  144. 'x:ip' => Yii::$app->services->base->getUserIp(),
  145. 'x:type' => $type,
  146. 'x:host' => $host,
  147. ];
  148. }
  149. /**
  150. * 截止日期
  151. *
  152. * @param $time
  153. * @return string
  154. * @throws \Exception
  155. */
  156. protected function expiration($time)
  157. {
  158. $dtStr = date("c", $time);
  159. $datatime = new \DateTime($dtStr);
  160. $expiration = $datatime->format(\DateTime::ISO8601);
  161. $pos = strpos($expiration, '+');
  162. $expiration = substr($expiration, 0, $pos);
  163. return $expiration . "Z";
  164. }
  165. }
粤ICP备19079148号