使用Devdefined OAuth库将文件上传到Dropbox

时间:2011-12-29 04:22:55

标签: c# rest dropbox devdefined-oauth

我正在尝试将文件上传到Dropbox REST Web服务,同时使用Devdefined的OAuth库。

这是我正在使用的方法:

    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 });
    }

该方法似乎没有做任何事情,也没有抛出任何异常。输出中也没有错误。我已经尝试使用断点来确认它也在调用代码。

1 个答案:

答案 0 :(得分:3)

您没有收到错误的原因是因为请求没有被执行 - 要执行获取响应所需的请求 - 有很多方法可以做到这一点,但通常最简单的方法就是获取使用ReadBody()方法返回文本。

上传文件内容无法作为查询参数完成 - 根据dropbox REST API,put请求的整个主体应该是文件的内容。

基本上为了这一切,你需要:

  • 根据您的Url中的API包含根路径“dropbox”或“sandbox”,我认为您缺少这些路径。如果您的DropBox应用程序已配置了应用程序文件夹,则使用“sandbox”。
  • 在使用者上下文中将“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-examples项目中添加了一个示例,演示了如何使用DropBox执行GET和PUT请求:

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);

希望这应该清楚一点,不幸的是没有文档,通过查看源代码来解决这些问题有点棘手:)