使用 OneDrive 下载共享文档 API

Download shared document with OneDrive API

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

我使用了 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...

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

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

https://api.onedrive.com/v1.0/drives/driveid/items/id/content

这会将您重定向到下载 URL,这将为您提供所需的内容。

问题解决后,我会返回并更新此答案。