前言
相信大家在使用阿里云OSS进行文件上传到时候,基本都是直接采用了阿里云提供的SDK;嗯,确实是简单方便,而且提供了各种语言、各种版本。但是偶尔会涉及到一些小众语言或者不方便集成SDK的项目,所以就需要直接采用Http进行上传。以下示例采用C#语言实现,若有其他语言参考即可:
开发环境:.NET Framework版本:4.8
开发工具:Visual Studio 2022
实现步骤
readonly string endpoint = "";
readonly string accessKeyId = "";
readonly string accessKeySecret = "";
readonly string bucketName = "";
private string HmacSha1(string data) { var hmacsha1 = new HMACSHA1(Encoding.UTF8.GetBytes(accessKeySecret)); var dataBuffer = Encoding.UTF8.GetBytes(data); var hashBytes = hmacsha1.ComputeHash(dataBuffer); return Convert.ToBase64String(hashBytes); }
private string Sign(string uploadName){ string data = $"PUT\n\ntext/plain\n{DateTime.Now.ToUniversalTime().ToString("r")}/{bucketName}/{uploadName}"; return HmacSha1(data);}
public async Task<string> Upload()
{
string uploadName = "test/123.txt";
string uploadPath = "d:\\123.txt";
string sign = Sign(uploadName);
string authorization = "OSS " + accessKeyId + ":" + sign;
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", authorization);
byte[] bytes = System.IO.File.ReadAllBytes(uploadPath);
HttpContent content = new ByteArrayContent(bytes);
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("text/plain");
var res = client.PutAsync(bucketEndpoint + uploadName, content).Result;
string result = await res.Content.ReadAsStringAsync();
return result;
}
实现效果
联系客服