public class LangChaoOssClient
{
public string EndPoint { get; }
public string AccessKeyID { get; }
private string AccessKeySecret { get; set; }
public LangChaoOssClient(string AccessKeyID, string accessKeySecret, string endPoint, bool isSsl = true)
{
EndPoint = endPoint;
this.AccessKeyID = AccessKeyID;
AccessKeySecret = accessKeySecret;
this.isSsl = isSsl;
}
private readonly bool isSsl;
public string Signature(string verb, string date, string contentMd5 = null, string contentType = null, string canonicalizedUCloudHeaders = null, string canonicalizedResource = null)
{
var s = new List<string>();
s.Add(verb);
s.Add(contentMd5 ?? "");
s.Add(contentType ?? "");
s.Add(date ?? "");
s.Add(canonicalizedUCloudHeaders + canonicalizedResource);
var sJoin = string.Join("\n", s);
var base64 = HmacSha1(AccessKeySecret, sJoin);
return base64;
}
static string HmacSha1(string key, string text)
{
Encoding encode = Encoding.UTF8;
byte[] byteData = encode.GetBytes(text);
byte[] byteKey = encode.GetBytes(key);
HMACSHA1 hmac = new HMACSHA1(byteKey);
CryptoStream cs = new CryptoStream(Stream.Null, hmac, CryptoStreamMode.Write);
cs.Write(byteData, 0, byteData.Length);
cs.Close();
return Convert.ToBase64String(hmac.Hash);
}
/// <summary>
/// putobj
/// </summary>
/// <param name="bucketName"></param>
/// <param name="objectKey"></param>
/// <param name="stream"></param>
/// <returns></returns>
public async Task<string> PutObjectAsync(string bucketName, string objectKey, Stream stream)
{
var h = isSsl ? "https" : "http";
var date = DateTime.UtcNow.ToString("r");
var urlPath = $"{h}://{bucketName}.{EndPoint}/{objectKey}";
// 特定请求的标头
var request = new HttpRequestMessage(HttpMethod.Put, urlPath);
request.Headers.Add("Date", date);
var fileContent = new ByteArrayContent(StreamToBytes(stream));
request.Content = fileContent;
request.Content.Headers.ContentType = new MediaTypeHeaderValue("binary/octet-stream");
request.Content.Headers.ContentLength = stream.Length;
var s = Signature(VERB.PUT, date,contentType: "binary/octet-stream", canonicalizedResource:$"/{bucketName}/{objectKey}");
request.Headers.Authorization = new AuthenticationHeaderValue(
"OSS",
$"{AccessKeyID}:{s}");
using var httpClient = new HttpClient();
// 发送请求
var response = await httpClient.SendAsync(request);
// 处理响应
response.EnsureSuccessStatusCode();
var val = await response.Content.ReadAsStringAsync();
return urlPath;
}
/// <summary>
/// 将 Stream 转成 byte[]
/// </summary>
byte[] StreamToBytes(Stream stream)
{
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
// 设置当前流的位置为流的开始
stream.Seek(0, SeekOrigin.Begin);
return bytes;
}
}
public class VERB
{
public const string GET = "GET";
public const string PUT = "PUT";
public const string DELETE = "DELETE";
public const string HEAD = "HEAD";
public const string PATCH = "PATCH";
}
浪潮云oss对象存储PutObject
最新推荐文章于 2023-11-08 19:00:49 发布