使用OneDrive API下载共享文档

时间:2017-03-15 13:33:10

标签: c# json onedrive

我正在尝试下载使用OneDrive API与用户共享的Word文档。

我使用了this页面中的文档。首先,我使用以下代码获取共享文件列表:

using (HttpClient client = new HttpClient())
{    
    client.BaseAddress = new Uri("https://api.onedrive.com");
    client.DefaultRequestHeaders.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer",
    <ACCESS TOKEN>);

    HttpResponseMessage response = await client.GetAsync("/v1.0/drive/oneDrive.sharedWithMe");
}

正如文档所说,我正在获取一个driveItem资源。可以找到文档here。响应是这个JSON:

{  
   "value":[  
      {  
         "@content.downloadUrl":"DOWNLOAD URL",
         "createdDateTime":"2017-03-09T09:08:19.227Z",
         "cTag":"CTAG",
         "eTag":"ETAG",
         "id":"ID",
         "lastModifiedDateTime":"2017-03-09T13:39:42.133Z",
         "name":"Word document.docx",
         "webUrl":"WEBURL",
         "remoteItem":{  
            "createdBy":{  
               "user":{  
                  "displayName":"username",
                  "id":"USERID"
               }
            },
            "fileSystemInfo":{  
               "createdDateTime":"2017-03-09T08:50:52.663Z",
               "lastModifiedDateTime":"2017-03-09T13:06:19.653Z"
            },
            "file":{  
               "hashes":{  
                  "sha1Hash":"23894BC4D8E941FFA861851F9B47DCBD9DB061C6"
               },
               "mimeType":"image/png"
            },
            "id":"REMOTE ID",
            "lastModifiedBy":{  
               "user":{  
                  "displayName":"username",
                  "id":"USER ID"
               }
            },
            "lastModifiedDateTime":"2017-03-09T13:39:28.497Z",
            "name":"Word document.docx",
            "parentReference":{  
               "driveId":"DRIVE ID"
            },
            "shared":{  
               "owner":{  
                  "user":{  
                     "displayName":"username",
                     "id":"DRIVE ID"
                  }
               }
            },
            "size":15854,
            "webUrl":"WEBURL"
         }
      }
   ]
}

我使用此JSON中的downloadUrl下载文件。 URL工作,所以我可以下载文件,起初它看起来像是一个word文档。但它实际上是一个png文件。我希望mime类型为application/vnd.openxmlformats-officedocument.wordprocessingml.document或属于.docx文档的任何其他mime类型。但是JSON说mime类型是image / png。所以我无法使用Word打开文件,但我必须将其作为图像打开。当作为图像打开时,我可以看到文件的内容,但我想要实际的Word文档。

我尝试以字节为单位下载文件并将其转换为Word文档。当然没有运气,因为下载的文件实际上是png ...

如何将共享文件下载为我期望的文档类型?

1 个答案:

答案 0 :(得分:1)

这看起来像服务中的一个错误,它以某种方式返回缩略图而不是内容。我们调查并解决您可以通过从driveId中提取remoteItem.parentReference值,从id中提取remoteItem值并制定如下请求来解决问题: / p>

  

https://api.onedrive.com/v1.0/drives/ driveid /项目/ id /内容

这会将您重定向到下载网址,该网址会为您提供所需内容。

在问题解决后,我会回过头来更新此答案。