UploadService.php 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. <?php
  2. namespace app\admin\service;
  3. use app\admin\model\SystemUploadfile;
  4. use OSS\Core\OssException;
  5. use OSS\Credentials\EnvironmentVariableCredentialsProvider;
  6. use OSS\OssClient;
  7. use think\facade\Env;
  8. use think\file\UploadedFile;
  9. use think\helper\Str;
  10. use Qcloud\Cos\Client;
  11. use Exception;
  12. use Qiniu\Storage\UploadManager;
  13. use Qiniu\Auth;
  14. class UploadService
  15. {
  16. public static ?UploadService $_instance = null;
  17. protected array $options = [];
  18. private array $saveData;
  19. public static function instance(): ?UploadService
  20. {
  21. if (!static::$_instance) static::$_instance = new static();
  22. return static::$_instance;
  23. }
  24. /**
  25. * @param array $options
  26. * @return $this
  27. */
  28. public function setConfig(array $options = []): UploadService
  29. {
  30. $this->options = $options;
  31. return $this;
  32. }
  33. /**
  34. * @return array
  35. */
  36. public function getConfig(): array
  37. {
  38. return $this->options;
  39. }
  40. /**
  41. * @param UploadedFile $file
  42. * @param string $base_path
  43. * @return string
  44. */
  45. protected function setFilePath(UploadedFile $file, string $base_path = ''): string
  46. {
  47. $path = date('Ymd') . '/' . Str::random(3) . time() . Str::random() . '.' . $file->extension();
  48. return $base_path . $path;
  49. }
  50. /**
  51. * @param UploadedFile $file
  52. * @return UploadService
  53. */
  54. protected function setSaveData(UploadedFile $file): static
  55. {
  56. $options = $this->options;
  57. $data = [
  58. 'upload_type' => $options['upload_type'],
  59. 'original_name' => $file->getOriginalName(),
  60. 'mime_type' => $file->getMime(),
  61. 'file_size' => $file->getSize(),
  62. 'file_ext' => strtolower($file->extension()),
  63. 'create_time' => time(),
  64. ];
  65. $this->saveData = $data;
  66. return $this;
  67. }
  68. /**
  69. * 本地存储
  70. *
  71. * @param UploadedFile $file
  72. * @param string $type
  73. * @return array
  74. */
  75. public function local(UploadedFile $file, string $type = ''): array
  76. {
  77. if ($file->isValid()) {
  78. $base_path = '/storage/' . date('Ymd') . '/';
  79. // 上传文件的目标文件夹
  80. $destinationPath = public_path() . $base_path;
  81. $this->setSaveData($file);
  82. // 将文件移动到目标文件夹中
  83. $move = $file->move($destinationPath, Str::random(3) . time() . Str::random() . session('admin.id') . '.' . $file->extension());
  84. $url = $base_path . $move->getFilename();
  85. $data = ['url' => $url];
  86. $this->save($url);
  87. return ['code' => 1, 'data' => $data];
  88. }
  89. $data = '上传失败';
  90. return ['code' => 0, 'data' => $data];
  91. }
  92. /**
  93. * 阿里云OSS
  94. *
  95. * @param UploadedFile $file
  96. * @param string $type
  97. * @return array
  98. */
  99. public function oss(UploadedFile $file, string $type = ''): array
  100. {
  101. $config = $this->getConfig();
  102. $accessKeyId = $config['oss_access_key_id'];
  103. $accessKeySecret = $config['oss_access_key_secret'];
  104. $endpoint = $config['oss_endpoint'];
  105. $bucket = $config['oss_bucket'];
  106. // 升级 aliyuncs/oss-sdk-php 到 v2.7.2 以上, 使用签名 v4 版本
  107. putenv('OSS_ACCESS_KEY_ID=' . $accessKeyId);
  108. putenv('OSS_ACCESS_KEY_SECRET=' . $accessKeySecret);
  109. $region = str_replace(['http://oss-', 'https://oss-', 'oss-'], '', explode('.aliyuncs.com', $endpoint)[0] ?? '');
  110. $provider = new EnvironmentVariableCredentialsProvider();
  111. $args = [
  112. "provider" => $provider,
  113. "endpoint" => $endpoint,
  114. "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
  115. "region" => $region
  116. ];
  117. if ($file->isValid()) {
  118. $object = $this->setFilePath($file, Env::get('EASYADMIN.OSS_STATIC_PREFIX', 'easyadmin8') . '/');
  119. try {
  120. $ossClient = new OssClient($args);
  121. $_rs = $ossClient->putObject($bucket, $object, file_get_contents($file->getRealPath()));
  122. $oss_request_url = $_rs['oss-request-url'] ?? '';
  123. if (empty($oss_request_url)) return ['code' => 0, 'data' => '上传至OSS失败'];
  124. $oss_request_url = str_replace('http://', 'https://', $oss_request_url);
  125. $this->setSaveData($file);
  126. } catch (OssException $e) {
  127. return ['code' => 0, 'data' => $e->getMessage()];
  128. }
  129. $data = ['url' => $oss_request_url];
  130. $this->save($oss_request_url);
  131. return ['code' => 1, 'data' => $data];
  132. }
  133. $data = '上传失败';
  134. return ['code' => 0, 'data' => $data];
  135. }
  136. /**
  137. * 腾讯云cos
  138. *
  139. * @param UploadedFile $file
  140. * @param string $type
  141. * @return array
  142. */
  143. public function cos(UploadedFile $file, string $type = ''): array
  144. {
  145. $config = $this->getConfig();
  146. $secretId = $config['cos_secret_id']; //替换为用户的 secretId,请登录访问管理控制台进行查看和管理,https://console.cloud.tencent.com/cam/capi
  147. $secretKey = $config['cos_secret_key']; //替换为用户的 secretKey,请登录访问管理控制台进行查看和管理,https://console.cloud.tencent.com/cam/capi
  148. $region = $config['cos_region']; //替换为用户的 region,已创建桶归属的region可以在控制台查看,https://console.cloud.tencent.com/cos5/bucket
  149. if ($file->isValid()) {
  150. $cosClient = new Client(
  151. [
  152. 'region' => $region,
  153. 'schema' => 'http',
  154. 'credentials' => ['secretId' => $secretId, 'secretKey' => $secretKey,
  155. ],
  156. ]);
  157. try {
  158. $object = $this->setFilePath($file, Env::get('EASYADMIN.OSS_STATIC_PREFIX', 'easyadmin8') . '/');
  159. $result = $cosClient->upload(
  160. $config['cos_bucket'], //存储桶名称,由BucketName-Appid 组成,可以在COS控制台查看 https://console.cloud.tencent.com/cos5/bucket
  161. $object, //此处的 key 为对象键
  162. file_get_contents($file->getRealPath())
  163. );
  164. $location = $result['Location'] ?? '';
  165. if (empty($location)) return ['code' => 0, 'data' => '上传至COS失败'];
  166. $location = 'https://' . $location;
  167. $this->setSaveData($file);
  168. }catch (Exception $e) {
  169. return ['code' => 0, 'data' => $e->getMessage()];
  170. }
  171. $data = ['url' => $location];
  172. $this->save($location);
  173. return ['code' => 1, 'data' => $data];
  174. }
  175. $data = '上传失败';
  176. return ['code' => 0, 'data' => $data];
  177. }
  178. /**
  179. * 七牛云
  180. *
  181. * @param UploadedFile $file
  182. * @param string $type
  183. * @return array
  184. * @throws Exception
  185. */
  186. public function qnoss(UploadedFile $file, string $type = ''): array
  187. {
  188. if (!$file->isValid()) return ['code' => 1, 'data' => '上传验证失败'];
  189. $uploadMgr = new UploadManager();
  190. $config = $this->getConfig();
  191. $accessKey = $config['qnoss_access_key'];
  192. $secretKey = $config['qnoss_secret_key'];
  193. $bucket = $config['qnoss_bucket'];
  194. $domain = $config['qnoss_domain'];
  195. $auth = new Auth($accessKey, $secretKey);
  196. $token = $auth->uploadToken($bucket);
  197. $object = $this->setFilePath($file, Env::get('EASYADMIN.OSS_STATIC_PREFIX', 'easyadmin8') . '/');
  198. list($ret, $error) = $uploadMgr->putFile($token, $object, $file->getRealPath());
  199. if (empty($ret)) return ['code' => 0, 'data' => $error->getResponse()->error ?? '上传失败,请检查七牛云相关参数配置'];
  200. $url = $domain . "/" . $ret['key'];
  201. $data = ['url' => $url];
  202. $this->setSaveData($file);
  203. $this->save($url);
  204. return ['code' => 1, 'data' => $data];
  205. }
  206. protected function save(string $url = ''): bool
  207. {
  208. $data = $this->saveData;
  209. $data['url'] = $url;
  210. $data['upload_time'] = time();
  211. return (new SystemUploadfile())->save($data);
  212. }
  213. }