Sample code for 30+ languages & platforms
Xojo Plugin Requires Chilkat v11.6.0+

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.

Microsoft documentation

Chilkat Xojo Plugin Downloads

Xojo Plugin
Dim success As Boolean
success = 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
    System.DebugLog("Could not load the private OneDrive token cache.")
    Return
End If

If ((token.JsonTypeOf("access_token") <> 1) Or (token.StringOfEquals("access_token","",True) = True)) Then
    System.DebugLog("Expected a nonempty access_token in the JSON.")
    Return
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
driveId = "YOUR_DRIVE_ID"
Dim parentId As String
parentId = "YOUR_PARENT_FOLDER_ID"
Dim fileName As String
fileName = "large.bin"
Dim filePath As String
filePath = "qa_data/large/sample.bin"
Dim receiptPath As String
receiptPath = "qa_data/oneDrive/upload-session.json"
Dim fac As New Chilkat.FileAccess
Dim sizeString As String
sizeString = fac.FileSizeStr(filePath)
If (fac.LastMethodSuccess <> True) Then
    System.DebugLog("Could not determine the source file size.")
    Return
End If

Dim sizeText As New Chilkat.StringBuilder
success = sizeText.Append(sizeString)
Dim match As New Chilkat.JsonObject
Dim matched As Int32
matched = sizeText.RegexMatch("\A[0-9]{1,9}\z",match,100)
If (matched <> 1) Then
    System.DebugLog("File size exceeds this example's supported range.")
    Return
End If

Dim fileSize As Int32
fileSize = sizeText.IntValue
If ((fileSize < 1) Or (fileSize > 999999999)) Then
    System.DebugLog("This example supports nonempty files up to 999,999,999 bytes; its int arithmetic is deliberately bounded.")
    Return
End If

success = fac.DirEnsureExists("qa_data/oneDrive")
If (success <> True) Then
    System.DebugLog("Could not create the private receipt directory.")
    Return
End If

Dim hash As New Chilkat.Crypt2
hash.HashAlgorithm = "sha256"
hash.EncodingMode = "hex"
Dim fileHash As String
fileHash = hash.HashFileENC(filePath)
If (hash.LastMethodSuccess <> True) Then
    System.DebugLog("Could not fingerprint the source file.")
    Return
End If

Dim receipt As New Chilkat.JsonObject
receipt.Strict = True
Dim resuming As Boolean
resuming = fac.FileExists(receiptPath)
If (resuming = True) Then
    success = receipt.LoadFile(receiptPath)
    If (success <> True) Then
        System.DebugLog("Invalid receipt; reconcile the target before another upload.")
        Return
    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
        System.DebugLog("Receipt does not match the drive, parent, name, and file; no request sent.")
        Return
    End If

    If (receipt.StringOfEquals("status","complete",True) = True) Then
        System.DebugLog("Already uploaded. Item ID: " + receipt.StringOf("itemId"))
        Return
    End If

    If (receipt.StringOfEquals("status","uploading",True) <> True) Then
        System.DebugLog("Previous session creation is uncertain; inspect the pending receipt before retrying.")
        Return
    End If

    If ((receipt.JsonTypeOf("uploadUrl") <> 1) Or (receipt.StringOfEquals("uploadUrl","",True) = True)) Then
        System.DebugLog("Expected a nonempty uploadUrl in the JSON.")
        Return
    End If

    If ((receipt.JsonTypeOf("expirationDateTime") <> 1) Or (receipt.StringOfEquals("expirationDateTime","",True) = True)) Then
        System.DebugLog("Expected a nonempty expirationDateTime in the JSON.")
        Return
    End If

Else
    Dim endpoint As New Chilkat.StringBuilder
    success = endpoint.Append("https://graph.microsoft.com/v1.0/drives/")
    success = endpoint.Append(http.UrlEncode(driveId))
    success = endpoint.Append("/items/")
    success = endpoint.Append(http.UrlEncode(parentId))
    success = endpoint.Append(":/")
    success = endpoint.Append(http.UrlEncode(fileName))
    success = endpoint.Append(":/createUploadSession")
    Dim body As New Chilkat.JsonObject
    success = body.UpdateString("item.name",fileName)
    success = body.UpdateString("item.""@microsoft.graph.conflictBehavior""","fail")
    success = receipt.UpdateString("driveId",driveId)
    success = receipt.UpdateString("parentId",parentId)
    success = receipt.UpdateString("name",fileName)
    success = receipt.UpdateString("fileHash",fileHash)
    success = receipt.UpdateInt("fileSize",fileSize)
    success = receipt.UpdateString("status","pending")
    success = receipt.WriteFile(receiptPath)
    If (success <> True) Then
        System.DebugLog("Could not save the pending receipt; no session created.")
        Return
    End If

    success = http.HttpJson("POST",endpoint.GetAsString(),body,"application/json",resp)
    If ((success <> True) And (resp.StatusCode = 0)) Then
        System.DebugLog("No HTTP response received; inspect diagnostics privately and reconcile writes before retrying.")
        Return
    End If

    If ((resp.StatusCode <> 200)) Then
        System.DebugLog("Unexpected HTTP status: " + Str(resp.StatusCode))
        System.DebugLog("Request ID: " + resp.GetHeaderField("request-id"))
        If (resp.StatusCode = 429) Then
            System.DebugLog("Retry-After: " + resp.GetHeaderField("Retry-After"))
        End If

        Return
    End If

    success = result.Load(resp.BodyStr)
    If (success <> True) Then
        System.DebugLog("Expected a well-formed JSON response.")
        Return
    End If

    If ((result.JsonTypeOf("uploadUrl") <> 1) Or (result.StringOfEquals("uploadUrl","",True) = True)) Then
        System.DebugLog("Expected a nonempty uploadUrl in the JSON.")
        Return
    End If

    If ((result.JsonTypeOf("expirationDateTime") <> 1) Or (result.StringOfEquals("expirationDateTime","",True) = True)) Then
        System.DebugLog("Expected a nonempty expirationDateTime in the JSON.")
        Return
    End If

    success = receipt.UpdateString("uploadUrl",result.StringOf("uploadUrl"))
    success = receipt.UpdateString("expirationDateTime",result.StringOf("expirationDateTime"))
    success = receipt.UpdateString("status","uploading")
    success = receipt.WriteFile(receiptPath)
    If (success <> True) Then
        System.DebugLog("Session created but receipt save failed; reconcile before another creation.")
        Return
    End If

End If

Dim uploadUrl As String
uploadUrl = receipt.StringOf("uploadUrl")
Dim serviceUrl As New Chilkat.Url
success = serviceUrl.ParseUrl(uploadUrl)
If (success <> True) Then
    System.DebugLog("Invalid returned service URL.")
    Return
End If

If ((serviceUrl.Ssl <> True) Or (serviceUrl.Host = "") Or (serviceUrl.Login <> "") Or (serviceUrl.Password <> "")) Then
    System.DebugLog("Expected an HTTPS service URL without embedded login credentials.")
    Return
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
success = serviceHost.Append(serviceUrl.Host)
Dim serviceQuery As New Chilkat.StringBuilder
success = serviceQuery.Append(serviceUrl.Query)
Dim authMatch As New Chilkat.JsonObject
Dim authMatched As Int32
authMatched = serviceQuery.RegexMatch("(?i)(?:^|[?&])tempauth=[^&]+",authMatch,100)
If (authMatched < 0) Then
    System.DebugLog("Could not inspect the service URL query.")
    Return
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
                System.DebugLog("Could not read the private SharePoint token cache.")
                Return
            End If

            If ((sharepointToken.JsonTypeOf("host") <> 1) Or (sharepointToken.StringOfEquals("host","",True) = True)) Then
                System.DebugLog("Expected a nonempty host in the JSON.")
                Return
            End If

            If ((sharepointToken.JsonTypeOf("access_token") <> 1) Or (sharepointToken.StringOfEquals("access_token","",True) = True)) Then
                System.DebugLog("Expected a nonempty access_token in the JSON.")
                Return
            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
    System.DebugLog("Invalid session expiry.")
    Return
End If

success = now.SetFromCurrentSystemTime()
If (success <> True) Then
    System.DebugLog("Could not check the expiry.")
    Return
End If

If (expires.DiffSeconds(now) <= 0) Then
    System.DebugLog("Session expired. Reconcile the destination before creating a replacement.")
    Return
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 Int32
offset = 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
        System.DebugLog("Session authentication or permission failure. HTTP status: " + Str(uploadResp.StatusCode))
        System.DebugLog("Refresh the correct service token or check grants, then resume this receipt. Do not recreate blindly.")
        Return
    End If

    If ((success <> True) And (uploadResp.StatusCode = 0)) Then
        System.DebugLog("No HTTP response received; inspect diagnostics privately and reconcile writes before retrying.")
        Return
    End If

    If ((uploadResp.StatusCode <> 200)) Then
        System.DebugLog("Unexpected HTTP status: " + Str(uploadResp.StatusCode))
        System.DebugLog("Request ID: " + uploadResp.GetHeaderField("request-id"))
        If (uploadResp.StatusCode = 429) Then
            System.DebugLog("Retry-After: " + uploadResp.GetHeaderField("Retry-After"))
        End If

        Return
    End If

    success = session.Load(uploadResp.BodyStr)
    If (success <> True) Then
        System.DebugLog("Expected a well-formed JSON response.")
        Return
    End If

Else
    success = 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
        System.DebugLog("Expected one remaining range; inspect session status before continuing.")
        Return
    End If

    success = range.SetString(session.StringOf("nextExpectedRanges[0]"))
    matched = range.RegexMatch("\A[0-9]{1,9}-\z",match,100)
    If (matched <> 1) Then
        System.DebugLog("Expected a single open-ended offset such as 3276800-; no more bytes sent.")
        Return
    End If

    Dim replacements As Int32
    replacements = range.Replace("-","")
    Dim nextOffset As Int32
    nextOffset = range.IntValue
    If ((nextOffset < offset) Or (nextOffset >= fileSize)) Then
        System.DebugLog("Unexpected server offset; retain the receipt and reconcile.")
        Return
    End If

    offset = nextOffset
    //  10 MiB is 32 * 320 KiB and is below the 60 MiB per-request limit.
    Dim chunkSize As Int32
    chunkSize = 10485760
    If ((fileSize - offset) < chunkSize) Then
        chunkSize = fileSize - offset
    End If

    Dim endByte As Int32
    endByte = offset + chunkSize - 1
    offsetText.Clear 
    success = offsetText.AppendInt(offset)
    countText.Clear 
    success = countText.AppendInt(chunkSize)
    success = chunkRequest.StreamChunkFromFile(filePath,offsetText.GetAsString(),countText.GetAsString())
    If (success <> True) Then
        System.DebugLog("Could not prepare the file chunk.")
        Return
    End If

    success = contentRange.SetString("bytes ")
    success = contentRange.AppendInt(offset)
    success = contentRange.Append("-")
    success = contentRange.AppendInt(endByte)
    success = contentRange.Append("/")
    success = contentRange.AppendInt(fileSize)
    chunkRequest.AddHeader "Content-Range",contentRange.GetAsString()
    success = uploadHttp.HttpReq(uploadUrl,chunkRequest,uploadResp)
    If ((uploadResp.StatusCode = 401) Or (uploadResp.StatusCode = 403)) Then
        System.DebugLog("Session authentication or permission failure. HTTP status: " + Str(uploadResp.StatusCode))
        System.DebugLog("Refresh the correct service token or check grants, then resume this receipt. Do not recreate blindly.")
        Return
    End If

    If ((success <> True) And (uploadResp.StatusCode = 0)) Then
        System.DebugLog("Upload response lost. Retain this receipt and query the session on the next run.")
        Return
    End If

    If ((uploadResp.StatusCode = 200) Or (uploadResp.StatusCode = 201)) Then
        If ((endByte + 1) <> fileSize) Then
            System.DebugLog("Unexpected early completion; reconcile the target.")
            Return
        End If

        success = result.Load(uploadResp.BodyStr)
        If (success <> True) Then
            System.DebugLog("Upload may have completed but its response is invalid; reconcile before retrying.")
            Return
        End If

        If ((result.JsonTypeOf("id") <> 1) Or (result.StringOfEquals("id","",True) = True)) Then
            System.DebugLog("Expected a nonempty id in the JSON.")
            Return
        End If

        success = receipt.UpdateString("status","complete")
        success = receipt.UpdateString("itemId",result.StringOf("id"))
        success = receipt.WriteFile(receiptPath)
        If (success <> True) Then
            System.DebugLog("Upload completed but saving its ID failed; reconcile before retrying.")
            Return
        End If

        System.DebugLog("Upload completed. Item ID: " + result.StringOf("id"))
        Return
    End If

    If ((success <> True) And (uploadResp.StatusCode = 0)) Then
        System.DebugLog("No HTTP response received; inspect diagnostics privately and reconcile writes before retrying.")
        Return
    End If

    If ((uploadResp.StatusCode <> 202)) Then
        System.DebugLog("Unexpected HTTP status: " + Str(uploadResp.StatusCode))
        System.DebugLog("Request ID: " + uploadResp.GetHeaderField("request-id"))
        If (uploadResp.StatusCode = 429) Then
            System.DebugLog("Retry-After: " + uploadResp.GetHeaderField("Retry-After"))
        End If

        Return
    End If

    success = session.Load(uploadResp.BodyStr)
    If (success <> True) Then
        System.DebugLog("Expected a well-formed JSON response.")
        Return
    End If

    If ((endByte + 1) = fileSize) Then
        System.DebugLog("Final bytes returned 202, not a completed item. Retain the session and inspect its status.")
        Return
    End If

    offset = endByte + 1
    If ((session.JsonTypeOf("expirationDateTime") <> 1) Or (session.StringOfEquals("expirationDateTime","",True) = True)) Then
        System.DebugLog("Expected a nonempty expirationDateTime in the JSON.")
        Return
    End If

    success = receipt.UpdateString("expirationDateTime",session.StringOf("expirationDateTime"))
    success = receipt.UpdateInt("confirmedOffset",offset)
    success = receipt.WriteFile(receiptPath)
    If (success <> True) Then
        System.DebugLog("Could not checkpoint progress; retain the prior receipt and query the server on resume.")
        Return
    End If

    System.DebugLog("Uploaded bytes so far: " + Str(offset))
Wend