'Upload file to SharePoint using HTTP Client is not working

I want to upload a static file to SharePoint using Graph API and HTTP Client. We have a folder where the file is kept, now we have to read the file from the folder and upload it to SharePoint.

Stream stream = GetFile() //this will return file data as a Stream.
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization
                     = new AuthenticationHeaderValue("Bearer", token);
MultipartFormDataContent form = new MultipartFormDataContent();
var streamContent = new StreamContent(stream);

var imageContent = new ByteArrayContent(streamContent.ReadAsByteArrayAsync().Result);
imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
form.Add(imageContent, "Test.pdf");

var response = httpClient.PostAsync(@"https://graph.microsoft.com/v1.0/sites/{siteId}/lists/{folderName}/drive/root:/childFolder/Test.pdf:/createUploadSession", form).Result;

We are getting BadRequest response for the above request.



Solution 1:[1]

According to the documentation no request body is required for createUploadSession endpoint but if you specify the body it must be json like this

Content-Type: application/json

{
  "item": {
    "@odata.type": "microsoft.graph.driveItemUploadableProperties",
    "@microsoft.graph.conflictBehavior": "rename",
    "name": "largefile.dat"
  }
}

The response will contain uploadSession resource type.

To upload the file, or a portion of the file, you need to make a PUT request to the uploadUrl value received in the createUploadSession response. You can upload the entire file, or split the file into multiple byte ranges, as long as the maximum bytes in any given request is less than 60 MiB.

Resources:

driveItemUploadableProperties

uploadSession

Upload bytes to the upload session

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user2250152