使用RestAPI将文件上传到OneDrive

时间:2019-05-19 12:33:20

标签: c# rest onedrive restsharp

我正在尝试使用以下代码将图像上传到OneDrive。该文件已成功上传到OneDrive文件夹,但是当我从OneDrive手动下载文件时,它以黑色打开并显示无效图像。

var client = new RestClient("https://graph.microsoft.com/v1.0" + $"/drives/{driveID}/items/{folderId}:/{originalFileName}:/content");
var request = new RestRequest(Method.PUT);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("Content-Type", Path.GetExtension(originalFileName).GetMimeType());
request.AddHeader("Authorization", "Bearer " + GetAccessToken());
request.AddFile("content", System.IO.File.ReadAllBytes(filePath), originalFileName);

var response = client.Execute(request);

我真的不知道我在这里犯了什么错误。你能帮我吗?

1 个答案:

答案 0 :(得分:0)

受此SO answer

的启发

我需要将其从HttpClient更改为RestClient。更改后,代码将如下所示:

using (var client = new HttpClient())
{
    var url = "https://graph.microsoft.com/v1.0" + $"/drives/{driveID}/items/{folderId}:/{originalFileName}:/content";
    client.DefaultRequestHeaders.Add("Authorization", "Bearer " + GetAccessToken());

    byte[] sContents = System.IO.File.ReadAllBytes(filePath);
    var content = new ByteArrayContent(sContents);

    var response = client.PutAsync(url, content).Result.Content.ReadAsStringAsync().Result;
}