using COSXML; using COSXML.Auth; using COSXML.Model.Object; using Infrastructure; using System; using System.IO; using System.Net; namespace ZR.Common { public class TencentCosHelper { static string secretId = AppSettings.GetConfig("TENCENT_COS:SECRET_ID"); static string secretKey = AppSettings.GetConfig("TENCENT_COS:SECRET_KEY"); static string region = AppSettings.GetConfig("TENCENT_COS:REGION"); static string bucketName1 = AppSettings.GetConfig("TENCENT_COS:BUCKET_NAME"); static string appId = AppSettings.GetConfig("TENCENT_COS:APPID"); /// /// 获取COS客户端 /// /// private static CosXmlServer GetCosXmlServer() { var config = new CosXmlConfig.Builder() .SetRegion(region) .Build(); var qCloudCredentialProvider = new DefaultQCloudCredentialProvider(secretId, secretKey, 600); return new CosXmlServer(config, qCloudCredentialProvider); } /// /// 上传到腾讯云COS /// /// 文件流 /// 存储路径 eg: upload/2020/01/01/xxx.png /// 存储桶 如果为空默认取配置文件 /// public static HttpStatusCode PutObjectFromFile(Stream filestreams, string dirPath, string bucketName = "") { if (string.IsNullOrEmpty(bucketName)) { bucketName = bucketName1; } try { dirPath = dirPath.Replace("\\", "/"); var cosXml = GetCosXmlServer(); var request = new PutObjectRequest(bucketName, dirPath, filestreams); request.APPID = appId; var result = cosXml.PutObject(request); return result.IsSuccessful() ? HttpStatusCode.OK : HttpStatusCode.BadRequest; } catch (COSXML.CosException.CosClientException ex) { Console.WriteLine("Failed with CosClientException: {0}", ex.Message); } catch (COSXML.CosException.CosServerException ex) { Console.WriteLine("Failed with CosServerException. ErrorCode: {0}; ErrorMessage: {1}; RequestID: {2}", ex.errorCode, ex.Message, ex.requestId); } catch (Exception ex) { Console.WriteLine("Failed with error info: {0}", ex.Message); } return HttpStatusCode.BadRequest; } /// /// 删除资源 /// /// 文件路径 /// 存储桶 如果为空默认取配置文件 /// public static HttpStatusCode DeleteFile(string dirPath, string bucketName = "") { if (string.IsNullOrEmpty(bucketName)) { bucketName = bucketName1; } try { dirPath = dirPath.Replace("\\", "/"); var cosXml = GetCosXmlServer(); var request = new DeleteObjectRequest(bucketName, dirPath); var result = cosXml.DeleteObject(request); return result.IsSuccessful() ? HttpStatusCode.OK : HttpStatusCode.BadRequest; } catch (COSXML.CosException.CosClientException ex) { Console.WriteLine("Failed with CosClientException: {0}", ex.Message); } catch (COSXML.CosException.CosServerException ex) { Console.WriteLine("Failed with CosServerException. ErrorCode: {0}; ErrorMessage: {1}; RequestID: {2}", ex.errorCode, ex.errorMessage, ex.requestId); } catch (Exception ex) { Console.WriteLine("Failed with error info: {0}", ex.Message); } return HttpStatusCode.BadRequest; } } }