OneDrive: Upload and Resume a File with an Upload Session
See more OneDrive Examples
Create a Graph upload session, stream sequential chunks, and resume using a saved private receipt. The returned session URL can require a SharePoint access token or carry legacy preauthentication. The example selects credentials for that exact service and uses them for both status queries and chunk uploads. Chunks are 10 MiB (a multiple of 320 KiB), except the final remainder. Intermediate responses are 202, and final completion is 200 or 201 with a DriveItem. Exact multiples of the chunk size are handled correctly.
The example deliberately supports nonempty files up to 999,999,999 bytes so all arithmetic fits int without using int64. This is a sample bound, not OneDrive's maximum file size. StreamChunkFromFile accepts decimal offset/count strings; larger implementations need exact decimal or wider arithmetic without truncation. Sizes in metadata remain strings. Keep the file unchanged during a transfer.
The receipt binds the drive, parent, filename, file size, and SHA-256 hash. Reusing a completed receipt does not upload again. On resumption, query the service for nextExpectedRanges rather than trusting a saved offset. This sample handles one open-ended remaining range and stops explicitly for multiple/bounded ranges. Expired, missing, conflicting, or uncertain sessions require reconciliation before starting again. Retain the private receipt; use one writer and atomic persistence per logical upload in production. A conflict policy of fail avoids replacing an existing target.
Returned service URLs are used unchanged with automatic redirects disabled. Graph URLs on graph.microsoft.com:443 use the Graph token. A separate SharePoint token is sent only to the exact configured host on port 443. Legacy URLs carrying tempauth are used without a bearer token, even when a SharePoint cache exists. Other content hosts receive no bearer token. HTTPS and absence of embedded login credentials are checked. Unexpected redirects stop rather than forwarding credentials.
For authenticated SharePoint transfers, prepare private qa_data/tokens/oneDrive-sharepoint.json containing host (a bare trusted hostname, such as tenant.sharepoint.com) and access_token issued for that SharePoint resource. Keep it separate from the Graph token cache. The app must obtain consent and acquire/refresh the SharePoint token separately; these transfer examples do not do that automatically. Use the appropriate tenant/resource/account and current permissions. On 401, renew the appropriate token or obtain a fresh legacy URL; do not blindly retry a write or forward the Graph token to SharePoint.
See the OneDrive guide: transfer authentication and Microsoft's current returned-URL behavior.
Keep drive IDs and item IDs as opaque strings, retaining the drive context with each item. Encode individual path segments, not an entire URL or a slash-separated path in one call. An item ID remains stable across rename/move within its drive; a name-based path changes. OneDrive does not use Outlook's ImmutableId preference.
Live operation: this changes OneDrive data. Select the target deliberately. The example does not automatically retry uncertain writes.
Permission: Delegated Files.ReadWrite for Graph; SharePoint permissions for authenticated session URLs. Review application permissions separately..
Uses direct Chilkat.Http requests to Microsoft Graph v1.0 in the global cloud. The delegated token is read from the private qa_data/tokens/oneDrive.json file created by the PKCE authorization example. Personal Microsoft accounts and Microsoft 365 work/school accounts can use delegated authorization when the app registration supports them. Refresh expired tokens; scopes and actual file access both matter.
For app-only Microsoft 365 access, use client credentials with administrator-approved application permissions. /me requires a signed-in user; app-only calls must address an authorized user, site, or drive explicitly. Client credentials do not grant access to personal OneDrive accounts. National clouds use their own authority and Graph hosts.
Check the expected HTTP status before using a response body. A false method result can still contain an HTTP error response; status zero means no response arrived. For 401, renew authorization; for 403, check permissions, access grants, and policy; for 429, honor Retry-After with a bounded retry. Reconcile uncertain writes before repeating them. Keep credentials, file contents, upload/download URLs, and detailed diagnostics private.
Chilkat VB.NET Downloads
Dim success As Boolean = False
' Assumes Chilkat is unlocked. See Global Unlock Sample.
success = False
' Obtain a delegated Graph token with this example's file permissions.
' See OneDrive OAuth2 with PKCE.
Dim token As New Chilkat.JsonObject
token.Strict = True
success = token.LoadFile("qa_data/tokens/oneDrive.json")
If (success <> True) Then
Debug.WriteLine("Could not load the private OneDrive token cache.")
Exit Sub
End If
If ((token.JsonTypeOf("access_token") <> 1) Or (token.StringOfEquals("access_token","",True) = True)) Then
Debug.WriteLine("Expected a nonempty access_token in the JSON.")
Exit Sub
End If
Dim http As New Chilkat.Http
http.AuthToken = token.StringOf("access_token")
http.RequireSslCertVerify = True
http.FollowRedirects = False
http.ConnectTimeout = 20
http.ReadTimeout = 120
http.SetRequestHeader("Accept","application/json")
Dim resp As New Chilkat.HttpResponse
Dim result As New Chilkat.JsonObject
result.Strict = True
Dim driveId As String = "YOUR_DRIVE_ID"
Dim parentId As String = "YOUR_PARENT_FOLDER_ID"
Dim fileName As String = "large.bin"
Dim filePath As String = "qa_data/large/sample.bin"
Dim receiptPath As String = "qa_data/oneDrive/upload-session.json"
Dim fac As New Chilkat.FileAccess
Dim sizeString As String = fac.FileSizeStr(filePath)
If (fac.LastMethodSuccess <> True) Then
Debug.WriteLine("Could not determine the source file size.")
Exit Sub
End If
Dim sizeText As New Chilkat.StringBuilder
sizeText.Append(sizeString)
Dim match As New Chilkat.JsonObject
Dim matched As Integer = sizeText.RegexMatch("\A[0-9]{1,9}\z",match,100)
If (matched <> 1) Then
Debug.WriteLine("File size exceeds this example's supported range.")
Exit Sub
End If
Dim fileSize As Integer = sizeText.IntValue
If ((fileSize < 1) Or (fileSize > 999999999)) Then
Debug.WriteLine("This example supports nonempty files up to 999,999,999 bytes; its int arithmetic is deliberately bounded.")
Exit Sub
End If
success = fac.DirEnsureExists("qa_data/oneDrive")
If (success <> True) Then
Debug.WriteLine("Could not create the private receipt directory.")
Exit Sub
End If
Dim hash As New Chilkat.Crypt2
hash.HashAlgorithm = "sha256"
hash.EncodingMode = "hex"
Dim fileHash As String = hash.HashFileENC(filePath)
If (hash.LastMethodSuccess <> True) Then
Debug.WriteLine("Could not fingerprint the source file.")
Exit Sub
End If
Dim receipt As New Chilkat.JsonObject
receipt.Strict = True
Dim resuming As Boolean = fac.FileExists(receiptPath)
If (resuming = True) Then
success = receipt.LoadFile(receiptPath)
If (success <> True) Then
Debug.WriteLine("Invalid receipt; reconcile the target before another upload.")
Exit Sub
End If
If ((receipt.StringOfEquals("driveId",driveId,True) <> True) Or (receipt.StringOfEquals("parentId",parentId,True) <> True) Or (receipt.StringOfEquals("name",fileName,True) <> True) Or (receipt.StringOfEquals("fileHash",fileHash,True) <> True) Or (receipt.IntOf("fileSize") <> fileSize)) Then
Debug.WriteLine("Receipt does not match the drive, parent, name, and file; no request sent.")
Exit Sub
End If
If (receipt.StringOfEquals("status","complete",True) = True) Then
Debug.WriteLine("Already uploaded. Item ID: " & receipt.StringOf("itemId"))
Exit Sub
End If
If (receipt.StringOfEquals("status","uploading",True) <> True) Then
Debug.WriteLine("Previous session creation is uncertain; inspect the pending receipt before retrying.")
Exit Sub
End If
If ((receipt.JsonTypeOf("uploadUrl") <> 1) Or (receipt.StringOfEquals("uploadUrl","",True) = True)) Then
Debug.WriteLine("Expected a nonempty uploadUrl in the JSON.")
Exit Sub
End If
If ((receipt.JsonTypeOf("expirationDateTime") <> 1) Or (receipt.StringOfEquals("expirationDateTime","",True) = True)) Then
Debug.WriteLine("Expected a nonempty expirationDateTime in the JSON.")
Exit Sub
End If
Else
Dim endpoint As New Chilkat.StringBuilder
endpoint.Append("https://graph.microsoft.com/v1.0/drives/")
endpoint.Append(http.UrlEncode(driveId))
endpoint.Append("/items/")
endpoint.Append(http.UrlEncode(parentId))
endpoint.Append(":/")
endpoint.Append(http.UrlEncode(fileName))
endpoint.Append(":/createUploadSession")
Dim body As New Chilkat.JsonObject
body.UpdateString("item.name",fileName)
body.UpdateString("item.""@microsoft.graph.conflictBehavior""","fail")
receipt.UpdateString("driveId",driveId)
receipt.UpdateString("parentId",parentId)
receipt.UpdateString("name",fileName)
receipt.UpdateString("fileHash",fileHash)
receipt.UpdateInt("fileSize",fileSize)
receipt.UpdateString("status","pending")
success = receipt.WriteFile(receiptPath)
If (success <> True) Then
Debug.WriteLine("Could not save the pending receipt; no session created.")
Exit Sub
End If
success = http.HttpJson("POST",endpoint.GetAsString(),body,"application/json",resp)
If ((success <> True) And (resp.StatusCode = 0)) Then
Debug.WriteLine("No HTTP response received; inspect diagnostics privately and reconcile writes before retrying.")
Exit Sub
End If
If ((resp.StatusCode <> 200)) Then
Debug.WriteLine("Unexpected HTTP status: " & resp.StatusCode)
Debug.WriteLine("Request ID: " & resp.GetHeaderField("request-id"))
If (resp.StatusCode = 429) Then
Debug.WriteLine("Retry-After: " & resp.GetHeaderField("Retry-After"))
End If
Exit Sub
End If
success = result.Load(resp.BodyStr)
If (success <> True) Then
Debug.WriteLine("Expected a well-formed JSON response.")
Exit Sub
End If
If ((result.JsonTypeOf("uploadUrl") <> 1) Or (result.StringOfEquals("uploadUrl","",True) = True)) Then
Debug.WriteLine("Expected a nonempty uploadUrl in the JSON.")
Exit Sub
End If
If ((result.JsonTypeOf("expirationDateTime") <> 1) Or (result.StringOfEquals("expirationDateTime","",True) = True)) Then
Debug.WriteLine("Expected a nonempty expirationDateTime in the JSON.")
Exit Sub
End If
receipt.UpdateString("uploadUrl",result.StringOf("uploadUrl"))
receipt.UpdateString("expirationDateTime",result.StringOf("expirationDateTime"))
receipt.UpdateString("status","uploading")
success = receipt.WriteFile(receiptPath)
If (success <> True) Then
Debug.WriteLine("Session created but receipt save failed; reconcile before another creation.")
Exit Sub
End If
End If
Dim uploadUrl As String = receipt.StringOf("uploadUrl")
Dim serviceUrl As New Chilkat.Url
success = serviceUrl.ParseUrl(uploadUrl)
If (success <> True) Then
Debug.WriteLine("Invalid returned service URL.")
Exit Sub
End If
If ((serviceUrl.Ssl <> True) Or (serviceUrl.Host = "") Or (serviceUrl.Login <> "") Or (serviceUrl.Password <> "")) Then
Debug.WriteLine("Expected an HTTPS service URL without embedded login credentials.")
Exit Sub
End If
' Returned URLs can be preauthenticated, Graph-authenticated, or SharePoint-authenticated.
' Never copy Graph authorization to an arbitrary host, and never follow redirects automatically.
Dim uploadHttp As New Chilkat.Http
uploadHttp.RequireSslCertVerify = True
uploadHttp.FollowRedirects = False
uploadHttp.ConnectTimeout = 20
uploadHttp.ReadTimeout = 120
Dim serviceHost As New Chilkat.StringBuilder
serviceHost.Append(serviceUrl.Host)
Dim serviceQuery As New Chilkat.StringBuilder
serviceQuery.Append(serviceUrl.Query)
Dim authMatch As New Chilkat.JsonObject
Dim authMatched As Integer = serviceQuery.RegexMatch("(?i)(?:^|[?&])tempauth=[^&]+",authMatch,100)
If (authMatched < 0) Then
Debug.WriteLine("Could not inspect the service URL query.")
Exit Sub
End If
' tempauth carries its own authorization. Do not add a bearer token to that legacy URL.
If (authMatched = 0) Then
If ((serviceHost.ContentsEqual("graph.microsoft.com",False) = True) And (serviceUrl.Port = 443)) Then
uploadHttp.AuthToken = token.StringOf("access_token")
Else
Dim tokenFiles As New Chilkat.FileAccess
If (tokenFiles.FileExists("qa_data/tokens/oneDrive-sharepoint.json") = True) Then
Dim sharepointToken As New Chilkat.JsonObject
sharepointToken.Strict = True
success = sharepointToken.LoadFile("qa_data/tokens/oneDrive-sharepoint.json")
If (success <> True) Then
Debug.WriteLine("Could not read the private SharePoint token cache.")
Exit Sub
End If
If ((sharepointToken.JsonTypeOf("host") <> 1) Or (sharepointToken.StringOfEquals("host","",True) = True)) Then
Debug.WriteLine("Expected a nonempty host in the JSON.")
Exit Sub
End If
If ((sharepointToken.JsonTypeOf("access_token") <> 1) Or (sharepointToken.StringOfEquals("access_token","",True) = True)) Then
Debug.WriteLine("Expected a nonempty access_token in the JSON.")
Exit Sub
End If
' Configure host independently; never trust a response URL to choose a new credential audience.
If ((serviceHost.ContentsEqual(sharepointToken.StringOf("host"),False) = True) And (serviceUrl.Port = 443)) Then
uploadHttp.AuthToken = sharepointToken.StringOf("access_token")
End If
End If
End If
End If
' Without a matching token, only a still-valid preauthenticated URL can succeed.
Dim expires As New Chilkat.CkDateTime
Dim now As New Chilkat.CkDateTime
success = expires.SetFromTimestamp(receipt.StringOf("expirationDateTime"))
If (success <> True) Then
Debug.WriteLine("Invalid session expiry.")
Exit Sub
End If
success = now.SetFromCurrentSystemTime()
If (success <> True) Then
Debug.WriteLine("Could not check the expiry.")
Exit Sub
End If
If (expires.DiffSeconds(now) <= 0) Then
Debug.WriteLine("Session expired. Reconcile the destination before creating a replacement.")
Exit Sub
End If
' The selected token applies to both session-status GETs and every chunk PUT.
' Reload refreshed credentials on the next run before querying the saved session.
Dim uploadResp As New Chilkat.HttpResponse
Dim session As New Chilkat.JsonObject
session.Strict = True
Dim offset As Integer = 0
If (resuming = True) Then
' Server status is authoritative after a lost response; a local offset might be stale.
success = uploadHttp.HttpNoBody("GET",uploadUrl,uploadResp)
If ((uploadResp.StatusCode = 401) Or (uploadResp.StatusCode = 403)) Then
Debug.WriteLine("Session authentication or permission failure. HTTP status: " & uploadResp.StatusCode)
Debug.WriteLine("Refresh the correct service token or check grants, then resume this receipt. Do not recreate blindly.")
Exit Sub
End If
If ((success <> True) And (uploadResp.StatusCode = 0)) Then
Debug.WriteLine("No HTTP response received; inspect diagnostics privately and reconcile writes before retrying.")
Exit Sub
End If
If ((uploadResp.StatusCode <> 200)) Then
Debug.WriteLine("Unexpected HTTP status: " & uploadResp.StatusCode)
Debug.WriteLine("Request ID: " & uploadResp.GetHeaderField("request-id"))
If (uploadResp.StatusCode = 429) Then
Debug.WriteLine("Retry-After: " & uploadResp.GetHeaderField("Retry-After"))
End If
Exit Sub
End If
success = session.Load(uploadResp.BodyStr)
If (success <> True) Then
Debug.WriteLine("Expected a well-formed JSON response.")
Exit Sub
End If
Else
session.UpdateString("nextExpectedRanges[0]","0-")
End If
Dim range As New Chilkat.StringBuilder
Dim contentRange As New Chilkat.StringBuilder
Dim offsetText As New Chilkat.StringBuilder
Dim countText As New Chilkat.StringBuilder
Dim chunkRequest As New Chilkat.HttpRequest
chunkRequest.HttpVerb = "PUT"
chunkRequest.ContentType = "application/octet-stream"
While (offset < fileSize)
' This sequential example handles a single open-ended remaining range.
' Stop rather than misinterpreting multiple holes or a bounded range.
If ((session.SizeOfArray("nextExpectedRanges") <> 1) Or (session.JsonTypeOf("nextExpectedRanges[0]") <> 1)) Then
Debug.WriteLine("Expected one remaining range; inspect session status before continuing.")
Exit Sub
End If
range.SetString(session.StringOf("nextExpectedRanges[0]"))
matched = range.RegexMatch("\A[0-9]{1,9}-\z",match,100)
If (matched <> 1) Then
Debug.WriteLine("Expected a single open-ended offset such as 3276800-; no more bytes sent.")
Exit Sub
End If
Dim replacements As Integer = range.Replace("-","")
Dim nextOffset As Integer = range.IntValue
If ((nextOffset < offset) Or (nextOffset >= fileSize)) Then
Debug.WriteLine("Unexpected server offset; retain the receipt and reconcile.")
Exit Sub
End If
offset = nextOffset
' 10 MiB is 32 * 320 KiB and is below the 60 MiB per-request limit.
Dim chunkSize As Integer = 10485760
If ((fileSize - offset) < chunkSize) Then
chunkSize = fileSize - offset
End If
Dim endByte As Integer = offset + chunkSize - 1
offsetText.Clear()
offsetText.AppendInt(offset)
countText.Clear()
countText.AppendInt(chunkSize)
success = chunkRequest.StreamChunkFromFile(filePath,offsetText.GetAsString(),countText.GetAsString())
If (success <> True) Then
Debug.WriteLine("Could not prepare the file chunk.")
Exit Sub
End If
contentRange.SetString("bytes ")
contentRange.AppendInt(offset)
contentRange.Append("-")
contentRange.AppendInt(endByte)
contentRange.Append("/")
contentRange.AppendInt(fileSize)
chunkRequest.AddHeader("Content-Range",contentRange.GetAsString())
success = uploadHttp.HttpReq(uploadUrl,chunkRequest,uploadResp)
If ((uploadResp.StatusCode = 401) Or (uploadResp.StatusCode = 403)) Then
Debug.WriteLine("Session authentication or permission failure. HTTP status: " & uploadResp.StatusCode)
Debug.WriteLine("Refresh the correct service token or check grants, then resume this receipt. Do not recreate blindly.")
Exit Sub
End If
If ((success <> True) And (uploadResp.StatusCode = 0)) Then
Debug.WriteLine("Upload response lost. Retain this receipt and query the session on the next run.")
Exit Sub
End If
If ((uploadResp.StatusCode = 200) Or (uploadResp.StatusCode = 201)) Then
If ((endByte + 1) <> fileSize) Then
Debug.WriteLine("Unexpected early completion; reconcile the target.")
Exit Sub
End If
success = result.Load(uploadResp.BodyStr)
If (success <> True) Then
Debug.WriteLine("Upload may have completed but its response is invalid; reconcile before retrying.")
Exit Sub
End If
If ((result.JsonTypeOf("id") <> 1) Or (result.StringOfEquals("id","",True) = True)) Then
Debug.WriteLine("Expected a nonempty id in the JSON.")
Exit Sub
End If
receipt.UpdateString("status","complete")
receipt.UpdateString("itemId",result.StringOf("id"))
success = receipt.WriteFile(receiptPath)
If (success <> True) Then
Debug.WriteLine("Upload completed but saving its ID failed; reconcile before retrying.")
Exit Sub
End If
Debug.WriteLine("Upload completed. Item ID: " & result.StringOf("id"))
Exit Sub
End If
If ((success <> True) And (uploadResp.StatusCode = 0)) Then
Debug.WriteLine("No HTTP response received; inspect diagnostics privately and reconcile writes before retrying.")
Exit Sub
End If
If ((uploadResp.StatusCode <> 202)) Then
Debug.WriteLine("Unexpected HTTP status: " & uploadResp.StatusCode)
Debug.WriteLine("Request ID: " & uploadResp.GetHeaderField("request-id"))
If (uploadResp.StatusCode = 429) Then
Debug.WriteLine("Retry-After: " & uploadResp.GetHeaderField("Retry-After"))
End If
Exit Sub
End If
success = session.Load(uploadResp.BodyStr)
If (success <> True) Then
Debug.WriteLine("Expected a well-formed JSON response.")
Exit Sub
End If
If ((endByte + 1) = fileSize) Then
Debug.WriteLine("Final bytes returned 202, not a completed item. Retain the session and inspect its status.")
Exit Sub
End If
offset = endByte + 1
If ((session.JsonTypeOf("expirationDateTime") <> 1) Or (session.StringOfEquals("expirationDateTime","",True) = True)) Then
Debug.WriteLine("Expected a nonempty expirationDateTime in the JSON.")
Exit Sub
End If
receipt.UpdateString("expirationDateTime",session.StringOf("expirationDateTime"))
receipt.UpdateInt("confirmedOffset",offset)
success = receipt.WriteFile(receiptPath)
If (success <> True) Then
Debug.WriteLine("Could not checkpoint progress; retain the prior receipt and query the server on resume.")
Exit Sub
End If
Debug.WriteLine("Uploaded bytes so far: " & offset)
End While