此SDK實現了七牛雲存儲的核心部分,即文件上傳,目的是簡化文件上傳並提供更加便捷的編程接口,從更高層面進行了抽象,而非官方SDK那樣,僅是對API的一套封裝。git
項目地址: https://github.com/icattlecoder/qiniu-csharp-sdkgithub
初始化工做包括對七牛的API Keys的賦值,如:編程
qiniu.Config.ACCESS_KEY = "IT9iP3J9wdXXYsT1p8ns0gWD-CQOdLvIQuyE0FOK"; qiniu.Config.SECRET_KEY = "zUCzekBtEqTZ4-WJPCGlBrr2PeyYxsYn98LPaivM";
QiniuFile qfile = new QiniuFile ("<input your bucket name>", "<input qiniu file key>", "<local disk file path>"); qfile.Upload();
一個QiniuFile對象表示一個七牛雲空間的文件,初始化QiniuFile提供如下三個參數:
- bucketName
,七牛雲空間名稱
- key
,七牛文件key
- localfile
,本地文件。該參數爲可選,若是要上傳本地的文件至七牛雲空間,則須要指定此參數的值。七牛雲存儲
注意上傳爲異步操做,上傳的結果由事件通知。異步
共包括五個事件spa
事件名稱 | 說明 |
---|---|
UploadCompleted; | 上傳完成 |
UploadFailed; | 上傳失敗 |
UploadProgressChanged; | 上傳進度 |
UploadBlockCompleted; | 上傳塊完成 |
UploadBlockFailed; | 上傳塊失敗 |
前三個事件比較容易理解,後兩個事件是根據七牛的大文件上傳機制衍生出來的,合理利用這兩個事件能夠完成大文件分塊上傳結果持久化,從而實現續傳。code
成功上傳一個文件後,結果經過事件uploadCompleted
獲取獲得,包括文件的Hash
和Key
以及從七牛雲存儲返回的原始字符串(主要考慮到上傳憑證中指定了自定義的returnBody)。對象
類QiniuResumbleUploadEx
可用於續傳,見示例。接口
簡單的實現了文件的基本信息獲取及刪除操做,分別爲Stat
和Delete
事件
using System; using System.Collections; using System.Collections.Generic; using qiniu; using System.Threading; namespace demo { class MainClass { public static void Main (string[] args) { // 初始化qiniu配置,主要是API Keys qiniu.Config.ACCESS_KEY = "IT9iP3J9wdXXYsT1p8ns0gWD-CQOdLvIQuyE0FOi"; qiniu.Config.SECRET_KEY = "zUCzekBtEqTZ4-WJPCGlBrr2PeyYxsYn98LPaivM"; /********************************************************************** 能夠用下面的方法從配置文件中初始化 qiniu.Config.InitFromAppConfig (); **********************************************************************/ string localfile = "/Users/icattlecoder/Movies/tzd.rmvb"; string bucket = "icattlecoder"; string qiniukey = "tzd.rmvb"; //====================================================================== { QiniuFile qfile = new QiniuFile (bucket, qiniukey, localfile); ResumbleUploadEx puttedCtx = new ResumbleUploadEx (localfile); //續傳 ManualResetEvent done = new ManualResetEvent (false); qfile.UploadCompleted += (sender, e) => { Console.WriteLine (e.key); Console.WriteLine (e.Hash); done.Set (); }; qfile.UploadFailed += (sender, e) => { Console.WriteLine (e.Error.ToString ()); puttedCtx.Save(); done.Set (); }; qfile.UploadProgressChanged += (sender, e) => { int percentage = (int)(100 * e.BytesSent / e.TotalBytes); Console.Write (percentage); }; qfile.UploadBlockCompleted += (sender, e) => { //上傳結果持久化 puttedCtx.Add(e.Index,e.Ctx); puttedCtx.Save(); }; qfile.UploadBlockFailed += (sender, e) => { // }; //上傳爲異步操做 //上傳本地文件到七牛雲存儲 qfile.Upload (); //若是要續傳,調用下面的方法 //qfile.Upload (puttedCtx.PuttedCtx); done.WaitOne (); } //====================================================================== { try { QiniuFile qfile = new QiniuFile (bucket, qiniukey); QiniuFileInfo finfo = qfile.Stat (); if (finfo != null) { qfile.Move("cloudcomment","movetest"); //刪除七牛雲空間的文件 //qfile.Delete (); } } catch (QiniuWebException e) { Console.WriteLine (e.Error.HttpCode); Console.WriteLine (e.Error.ToString ()); } } } } }