+
diff --git a/application/common/library/Upload.php b/application/common/library/Upload.php
index f9c75d4..c43d39d 100644
--- a/application/common/library/Upload.php
+++ b/application/common/library/Upload.php
@@ -446,10 +446,69 @@ class Upload
$attachment->data(array_filter($params));
$attachment->save();
+ $this->syncToCos($attachment);
+
\think\Hook::listen("upload_after", $attachment);
return $attachment;
}
+ /**
+ * 同步文件到腾讯云COS
+ * @param Attachment $attachment
+ */
+ protected function syncToCos($attachment)
+ {
+ try {
+ $addonInfo = get_addon_info('cos');
+ if (!$addonInfo || empty($addonInfo['state'])) {
+ return;
+ }
+ $cosConfig = get_addon_config('cos');
+ if (empty($cosConfig) || empty($cosConfig['secretId']) || empty($cosConfig['secretKey']) || empty($cosConfig['bucket'])) {
+ return;
+ }
+
+ if (!class_exists('\Qcloud\Cos\Client')) {
+ $cosAddonPath = (defined('ADDON_PATH') ? ADDON_PATH : (ROOT_PATH . 'addons' . DS)) . 'cos' . DIRECTORY_SEPARATOR;
+ \think\Loader::addNamespace('Qcloud\Cos', $cosAddonPath . 'library' . DIRECTORY_SEPARATOR . 'Qcloud' . DIRECTORY_SEPARATOR . 'Cos' . DIRECTORY_SEPARATOR);
+ \think\Loader::addNamespace('GuzzleHttp\Command', $cosAddonPath . 'library' . DIRECTORY_SEPARATOR . 'Guzzle' . DIRECTORY_SEPARATOR . 'command' . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR);
+ \think\Loader::addNamespace('GuzzleHttp\Command\Guzzle', $cosAddonPath . 'library' . DIRECTORY_SEPARATOR . 'Guzzle' . DIRECTORY_SEPARATOR . 'guzzle-services' . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR);
+ \think\Loader::addNamespace('GuzzleHttp\UriTemplate', $cosAddonPath . 'library' . DIRECTORY_SEPARATOR . 'Guzzle' . DIRECTORY_SEPARATOR . 'uri-template' . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR);
+ }
+
+ $realPath = ROOT_PATH . 'public' . str_replace('/', DS, $attachment->url);
+ if (!file_exists($realPath)) {
+ return;
+ }
+
+ $client = new \Qcloud\Cos\Client([
+ 'region' => $cosConfig['region'],
+ 'schema' => 'https',
+ 'credentials' => [
+ 'secretId' => $cosConfig['secretId'],
+ 'secretKey' => $cosConfig['secretKey'],
+ ]
+ ]);
+
+ $key = ltrim($attachment->url, '/');
+ $fileHandle = fopen($realPath, 'rb');
+ $client->upload($cosConfig['bucket'], $key, $fileHandle);
+ if (is_resource($fileHandle)) {
+ fclose($fileHandle);
+ }
+
+ $attachment->storage = 'cos';
+ $attachment->save();
+
+ // 如果设置了不保留本地备份,则删除本地文件
+ if (isset($cosConfig['serverbackup']) && $cosConfig['serverbackup'] == 0) {
+ @unlink($realPath);
+ }
+ } catch (\Exception $e) {
+ \think\Log::write('COS Upload Error: ' . $e->getMessage(), 'error');
+ }
+ }
+
/**
* 设置错误信息
* @param $msg