2011-12-29 90 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