How To Upload Files To OneDrive Or SharePoint Using Microsoft Graph API And CSOM
Uploading files in Sharepoint can be quite a difficulty. There are different ways to Upload files, Like CSOM (Client Side Object Model) or the Graph API.
CSOM works directly with the SharePoint APIs, while Graph is more like a Wrapper and its own service.
There are different functions in CSOM to upload Files. Here is shown, which Function should be used in which case:
When working with CSOM, I would use the Content Attribute of the FileCreationInformation class to upload a File, which is smaller than 10 MB.
For Files bigger than 10 MB I would use the Chunking methods of the File class.
The following code is from Microsoft and can be viewed in their Official Documentation
In the body of the Command, you need to define a Conflictbehavior, the FIlename, and the Filesize as a JSON Object.
There Location, where the file will be Uploaded, is set through the URL of the CreateUploadSession Command. This is how the URL is built:
“https://graph.microsoft.com/v1.0/sites/", siteID, “/drives/”, drive, “/root:/”, folder path, “/”, filename, “:/createUploadSession”
In it, the SiteId, DriveId, Folterpath, and Filename hast to be defined.
The successful call will return a UploadUrl. This Url can now be used to Upload Chunks of a file.
For this, there will be a new Call set against Graph API. The Destination is the achieved URL from the previous step. The next thing is, that the Chunk will be set into a UINT8 Array. This can be achieved by the following method:
var data = new Uint8Array(bytearray);
The bytearray is in this case the chunk. In addition, we need to set the following headers:
xhr.setRequestHeader(‘Content-Range’, ‘’.concat(“bytes “, from, “-”, to, “/”, totalFileSize));
Bytes from and to define, which Chunks we are sending right now.
for example from 0–1023. next would be then 1024–2047.
In Contentlength has to be the total File Size.
Now we can upload Chunk for Chunk to the Url until the whole file is uploaded.
If we want to abort the Upload, we can just send a delete HTTP Request to the URL.
When a Request fails, you can just retry it. If the createUpload Request is not fulfilled within a period of time, the Upload will be aborted. During that time, no other Upload can be started against the same Location.