将文件保存到阿里云上。

1.添加对象存储OSS空间 (新建Bucket)

可以在阿里云后台对象存储里面添加,也可以通过api添加。添加之后设置权限。

 

skd使用。

1安装 Aliyun.OSS.SDK (framework版,如果需要可以选择core版)

2.初始化。

在存储空间概览页面找到 EndPoint。

 

在设置appid和密钥

 

 

const string accessKeyId = "<your AccessKeyId>";

const string accessKeySecret = "<your AccessKeySecret>";

const string endpoint = "http://oss-cn-hangzhou.aliyuncs.com";

  • /// <summary>
  • /// 由用户指定的OSS访问地址、阿里云颁发的AccessKeyId/AccessKeySecret构造一个新的OssClient实例。
  • /// </summary>
  • /// <param name="endpoint">OSS的访问地址。</param>
  • /// <param name="accessKeyId">OSS的访问ID。</param>
  • /// <param name="accessKeySecret">OSS的访问密钥。</param>
  • var ossClient = new OssClient(endpoint, accessKeyId, accessKeySecret);

3.上传文件

 

// 初始化OssClient
var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
try
{
    string fileToUpload = "your local file path";
    client.PutObject(bucketName, key, fileToUpload);
    Console.WriteLine("Put object succeeded");
}
catch (Exception ex)
{
    Console.WriteLine("Put object failed, {0}", ex.Message);
}
上传本地文件

 

// 初始化OssClient
var client = new OssClient(endpoint, accessKeyId, accessKeySecret)
try
{
    string str = "a line of simple text";
    byte[] binaryData = Encoding.ASCII.GetBytes(str);            
    MemoryStream requestContent = new MemoryStream(binaryData);
    client.PutObject(bucketName, key, requestContent);
    Console.WriteLine("Put object succeeded");
}
catch (Exception ex)
{
    Console.WriteLine("Put object failed, {0}", ex.Message);
}
上传文件(byte[],stream等)

其中key是要上传的文件名(可以要后缀也可以不要)

 

 

4.访问文件

 

OssClient client = new OssClient(endpoint, accessKeyId, accessKeySecret);
    var listResult = client.ListObjects(bucketName);
    foreach (var summary in listResult.ObjectSummaries)
    {   
        Console.WriteLine(summary.Key);
    }
View Code

 

 

 

5.删除文件

 

OssClient client = new OssClient(endpoint, accessKeyId, accessKeySecret);
	client.DeleteObject(bucketName, key)

 

参考:

对象存储 OSS > SDK 参考 > .NET: https://help.aliyun.com/document_detail/32087.html?spm=a2c4g.11186623.6.864.56364144Mi9xWt

github demo: https://github.com/aliyun/aliyun-oss-csharp-sdk

 

posted on 2018-09-09 23:12  余昭(Ray)  阅读(2644)  评论(1编辑  收藏  举报