阿里雲Oss對象存儲

將文件保存到阿里雲上。html

1.添加對象存儲OSS空間 (新建Bucket)git

能夠在阿里雲後臺對象存儲裏面添加,也能夠經過api添加。添加以後設置權限。github

 

skd使用。api

1安裝 Aliyun.OSS.SDK (framework版,若是須要能夠選擇core版)app

2.初始化。ide

在存儲空間概覽頁面找到 EndPoint。阿里雲

 

在設置appid和密鑰spa

 

 

const string accessKeyId = "<your AccessKeyId>";3d

const string accessKeySecret = "<your AccessKeySecret>";code

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

相關文章
相關標籤/搜索