2011-12-29 34 views
1

我試圖將文件上傳到Dropbox REST Web服務,同時使用Devdefined的OAuth庫。使用Devdefined OAuth庫將文件上傳到Dropbox

這是我使用的方法:

public static void UploadFile(string filenameIn, string directoryIn, byte[] dataIn) 
    { 
     DropBox.session.Request().Put().ForUrl("https://api-content.dropbox.com/1/files_put/" + directoryIn + filenameIn) 
      .WithQueryParameters(new { param = dataIn }); 
    } 

的方法似乎並不做任何事情,也沒有引發任何異常。輸出中也沒有錯誤。我試過使用斷點來確認它也調用了代碼。

回答

3

你沒有收到錯誤的原因是因爲請求沒有被執行 - 執行請求你需要獲取響應 - 有很多方法可以做到這一點,但通常最簡單的方法就是獲取使用方法ReadBody()返回文本。

上傳文件的內容不能作爲查詢參數完成 - 根據Dropbox REST API,put請求的整個主體應該是文件的內容。

從本質上講這一切工作,你將需要:

  • 包含根路徑「的Dropbox」或「沙箱」按你的地址,我認爲你缺少的API。如果您的DropBox應用程序已配置了應用程序文件夾,則使用「沙盒」。
  • 在用戶上下文中將「UseHeaderForOAuthParameters」設置爲true,以確保OAuth簽名等作爲請求標頭傳遞,而不是作爲表單參數編碼(因爲整個主體是原始數據)。
  • 使用「WithRawContent(byte [] contents)」方法將文件的內容添加到請求中。
  • 在PUT請求方法鏈的最末端使用「ReadBody()」方法來導致請求被執行。

結果將是一個包含JSON字符串應該是這個樣子:

{ 
    "revision": 5, 
    "rev": "5054d8c6e", 
    "thumb_exists": true, 
    "bytes": 5478, 
    "modified": "Thu, 29 Dec 2011 10:42:05 +0000", 
    "path": "/img_fa06e557-6736-435c-b539-c1586a589565.png", 
    "is_dir": false, 
    "icon": "page_white_picture", 
    "root": "app_folder", 
    "mime_type": "image/png", 
    "size": "5.3KB" 
} 

我已經在GitHub上添加了個例子,DevDefined.OAuth-例子工程演示如何做得到和PUT請求與DropBox的:

https://github.com/bittercoder/DevDefined.OAuth-Examples/blob/master/src/ExampleDropBoxUpload/Program.cs

下面是特別需要的PUT請求的代碼:

var consumerContext = new OAuthConsumerContext 
{ 
    SignatureMethod = SignatureMethod.HmacSha1, 
    ConsumerKey = "key goes here", 
    ConsumerSecret = "secret goes here", 
    UseHeaderForOAuthParameters = true 
}; 

var session = new OAuthSession(consumerContext, "https://api.dropbox.com/1/oauth/request_token", 
    "https://www.dropbox.com/1/oauth/authorize", 
    "https://api.dropbox.com/1/oauth/access_token"); 

IToken requestToken = session.GetRequestToken(); 

string authorisationUrl = session.GetUserAuthorizationUrlForToken(requestToken); 

Console.WriteLine("Authorization Url: {0}", authorisationUrl); 

// ... Authorize request... and then... 

session.ExchangeRequestTokenForAccessToken(requestToken); 

string putUrl = "https://api-content.dropbox.com/1/files_put/sandbox/some-image.png"; 

byte[] contents = File.ReadAllBytes("some-image.png"); 

IConsumerRequest putRequest = session.Request().Put().ForUrl(putUrl).WithRawContent(contents); 

string putInfo = putRequest.ReadBody(); 

Console.WriteLine("Put response: {0}", putInfo); 

希望這應該清除了一點東西,可惜沒有證件這是一個有點棘手通過看源代碼:)

+0

三江源這麼多,這個固定我的問題這些事情弄清楚! – 2011-12-29 21:56:11

+0

沒問題,樂於幫忙 – Bittercoder 2011-12-30 03:51:52