简体   繁体   中英

Upload file to OneDrive using RestAPI

I am trying to upload an image to OneDrive using below code. The file was successfully uploaded to the OneDrive folder but when I download the file manually from OneDrive, it opens in black color and shows Invalid Image.

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

I really do not know what mistake I am making in here. May you please help me?

Inspired from this SO answer

I need to change it to HttpClient from RestClient . After change the code will like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM