首先引用阿里云开源Nuget包Aliyun.OSS.SDK
然后在OSS中配置使用OSS上传必要的配置,具体文档查看地址:https://help.aliyun.com/document_detail/31947.html?spm=a2c4g.11186623.6.1574.32fe34704pHexv
这些都已具备后,直接进行上传,代码示例如下:
static string accessKeyId = ConfigurationManager.AppSettings["AccessKeyId"];
static string accessKeySecret = ConfigurationManager.AppSettings["AccessKeySecret"];
static string endpoint = ConfigurationManager.AppSettings["Endpoint"];
static string bucketName_file = ConfigurationManager.AppSettings["Bucket_Picture"];//OSS图片存储空间
static OssClient client = new OssClient(endpoint, accessKeyId, accessKeySecret);
/// <summary>
/// 文件简单上传
/// </summary>
/// <param name="bucketName">存储空间</param>
/// <param name="fileName">文件名(若要新建文件夹:文件夹名/文件名)</param>
/// <param name="content">上传的文件</param>
/// <returns></returns>
public bool PutObjectFromFile(string bucketName, string fileName, Stream content)
{
try
{
bool result = false;
var obj = client.PutObject(bucketName, fileName, content);
if (obj != null && obj.HttpStatusCode == HttpStatusCode.OK)
{
result = true;
}
return result;
}
catch (OssException ex)
{
WriteDataLog.WriteLog(string.Format("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3},BucketName:{4},fileName:{5}",
ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId, bucketName, fileName));
return false;
}
catch (Exception ex)
{
WriteDataLog.WriteLog(string.Format("Failed with error info: {0},BucketName:{1},fileName:{2}", ex.Message, bucketName, fileName));
return false;
}
}
相关代码其实比较少,但是配置相关的东西一定要配置对,否则会一直报错。
如果有什么不清楚的地方,欢迎留言探讨。