using Tencent.QCloud.Cos.Sdk (5.4.13)
初始化
using COSXML;
using COSXML.Auth;
using COSXML.CosException;
using COSXML.Model.Bucket;
using COSXML.Model.Object;
using COSXML.Transfer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
public class CosAdapter : IFileAdapter
{
private readonly CosXml _cosXml;
private readonly ILogger<CosAdapter> _logger;
public string Endpoint => throw new NotImplementedException();
/// <summary>
/// 存储桶地域
/// </summary>
public string Region { get; private set; }
/// <summary>
/// 存储桶 (BucketName-APPID)
/// </summary>
public string Bucket { get; private set; }
/// <summary>
/// 腾讯云账户的账户标识 APPID
/// </summary>
public string AppId { get; private set; }
/// <summary>
/// 云 API 密钥ID
/// </summary>
public string SecretId { get; private set; }
/// <summary>
/// 云 API 密钥Key
/// </summary>
public string SecretKey { get; private set; }
public CosAdapter(ILogger<CosAdapter> logger, IConfiguration configuration)
{
_logger = logger;
string region = configuration.GetSection("Endpoint").Value;
string bucketName = configuration.GetSection("BucketName").Value;
string appId = configuration.GetSection("AppId").Value;
string secretId = configuration.GetSection("AccessKeyId").Value;
string secretKey = configuration.GetSection("AccessKeySecret").Value;
Region = region;
Bucket = $"{bucketName}-{appId}";
AppId = appId;
SecretId = secretId;
SecretKey = secretKey;
CosXmlConfig config = new CosXmlConfig.Builder()
.SetRegion(region)
.SetAppid(appId)
.IsHttps(true)
.SetDebugLog(true)
.SetReadWriteTimeoutMs(600 * 1000)
.Build();
// 每次请求签名有效时长,单位为秒
long durationSecond = 600;
// 永久密钥
var qCloudCredentialProvider = new DefaultQCloudCredentialProvider(secretId, secretKey, durationSecond);
_cosXml = new CosXmlServer(config, qCloudCredentialProvider);
}
}
文件是否存在
public bool FileExist(string key)
{
try
{
var request = new HeadObjectRequest(Bucket, key);
var result = _cosXml.HeadObject(request);
return result.httpCode == 200;
}
catch (CosClientException ex)
{
Console.WriteLine("CosClientException: " + ex);
}
catch (CosServerException ex)
{
Console.WriteLine("CosServerException: " + ex.GetInfo());
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex);
}
return false;
}
文件大小
private long GetLength(string key)
{
try
{
var request = new HeadObjectRequest(Bucket, key);
var result = _cosXml.HeadObject(request);
var list = result.responseHeaders["Content-Length"];
if (list != null && list.Count > 0)
{
return Convert.ToInt64(list[0]);
}
}
catch (CosClientException ex)
{
Console.WriteLine("CosClientException: " + ex);
}
catch (CosServerException ex)
{
Console.WriteLine("CosServerException: " + ex.GetInfo());
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex);
}
return 0;
}
简单上传
private async Task<string> PutObject(string key, byte[] byteData, int outTime = 2000)
{
try
{
var request = new PutObjectRequest(Bucket, key, byteData);
// 设置进度回调
request.SetCosProgressCallback((completed, total) =>
{
Console.WriteLine(string.Format("progress={0:##.##}%", completed * 100.0 / total));
});
// 执行请求
var result = await Task.FromResult(_cosXml.PutObject(request));
if (result.httpCode == 200)
{
return key;
}
}
catch (CosClientException ex)
{
return "CosClientException: " + ex.Message;
}
catch (CosServerException ex)
{
return "CosServerException: " + ex.GetInfo();
}
catch (Exception ex)
{
return ex.Message;
}
return "ERROR";
}
部分上传
public async Task<string> AddFile(string fileName, string key, Stream fileToUpload, int outTime = 20_000)
{
if (fileToUpload is null)
{
throw new ArgumentNullException(nameof(fileToUpload));
}
var transferConfig = new TransferConfig();
var transferManager = new TransferManager(_cosXml, transferConfig);
if (string.IsNullOrEmpty(key))
{
key = GetName(fileName, TmpFileDirectory);
}
var uploadTask = new COSXMLUploadTask(Bucket, key);
var srcPath = @"D:\WESSON\Download\Programs\" + fileName;
var fileOffset = GetLength(key);
uploadTask.SetSrcPath(srcPath, fileOffset, fileToUpload.Length);
uploadTask.progressCallback = delegate (long completed, long total)
{
Console.WriteLine(String.Format("progress = {0:##.##}%", completed * 100.0 / total));
};
try
{
transferManager.Upload(uploadTask);
}
catch (Exception e)
{
Console.WriteLine("CosException: " + e);
}
return key;
}
分片上传