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 AutoIt Downloads
Local $bSuccess = False
; Assumes Chilkat is unlocked. See Global Unlock Sample.
$bSuccess = False
; Obtain a delegated Graph token with this example's file permissions.
; See OneDrive OAuth2 with PKCE.
$oToken = ObjCreate("Chilkat.JsonObject")
$oToken.Strict = True
$bSuccess = $oToken.LoadFile("qa_data/tokens/oneDrive.json")
If ($bSuccess <> True) Then
ConsoleWrite("Could not load the private OneDrive token cache." & @CRLF)
Exit
EndIf
If (($oToken.JsonTypeOf("access_token") <> 1) Or ($oToken.StringOfEquals("access_token","",True) = True)) Then
ConsoleWrite("Expected a nonempty access_token in the JSON." & @CRLF)
Exit
EndIf
$oHttp = ObjCreate("Chilkat.Http")
$oHttp.AuthToken = $oToken.StringOf("access_token")
$oHttp.RequireSslCertVerify = True
$oHttp.FollowRedirects = False
$oHttp.ConnectTimeout = 20
$oHttp.ReadTimeout = 120
$oHttp.SetRequestHeader "Accept","application/json"
$oResp = ObjCreate("Chilkat.HttpResponse")
$oResult = ObjCreate("Chilkat.JsonObject")
$oResult.Strict = True
Local $sDriveId = "YOUR_DRIVE_ID"
Local $sParentId = "YOUR_PARENT_FOLDER_ID"
Local $sFileName = "large.bin"
Local $sFilePath = "qa_data/large/sample.bin"
Local $sReceiptPath = "qa_data/oneDrive/upload-session.json"
$oFac = ObjCreate("Chilkat.FileAccess")
Local $sizeString = $oFac.FileSizeStr($sFilePath)
If ($oFac.LastMethodSuccess <> True) Then
ConsoleWrite("Could not determine the source file size." & @CRLF)
Exit
EndIf
$oSizeText = ObjCreate("Chilkat.StringBuilder")
$oSizeText.Append($sizeString)
$oMatch = ObjCreate("Chilkat.JsonObject")
Local $iMatched = $oSizeText.RegexMatch("\A[0-9]{1,9}\z",$oMatch,100)
If ($iMatched <> 1) Then
ConsoleWrite("File size exceeds this example's supported range." & @CRLF)
Exit
EndIf
Local $iFileSize = $oSizeText.IntValue
If (($iFileSize < 1) Or ($iFileSize > 999999999)) Then
ConsoleWrite("This example supports nonempty files up to 999,999,999 bytes; its int arithmetic is deliberately bounded." & @CRLF)
Exit
EndIf
$bSuccess = $oFac.DirEnsureExists("qa_data/oneDrive")
If ($bSuccess <> True) Then
ConsoleWrite("Could not create the private receipt directory." & @CRLF)
Exit
EndIf
$oHash = ObjCreate("Chilkat.Crypt2")
$oHash.HashAlgorithm = "sha256"
$oHash.EncodingMode = "hex"
Local $sFileHash = $oHash.HashFileENC($sFilePath)
If ($oHash.LastMethodSuccess <> True) Then
ConsoleWrite("Could not fingerprint the source file." & @CRLF)
Exit
EndIf
$oReceipt = ObjCreate("Chilkat.JsonObject")
$oReceipt.Strict = True
Local $bResuming = $oFac.FileExists($sReceiptPath)
If ($bResuming = True) Then
$bSuccess = $oReceipt.LoadFile($sReceiptPath)
If ($bSuccess <> True) Then
ConsoleWrite("Invalid receipt; reconcile the target before another upload." & @CRLF)
Exit
EndIf
If (($oReceipt.StringOfEquals("driveId",$sDriveId,True) <> True) Or ($oReceipt.StringOfEquals("parentId",$sParentId,True) <> True) Or ($oReceipt.StringOfEquals("name",$sFileName,True) <> True) Or ($oReceipt.StringOfEquals("fileHash",$sFileHash,True) <> True) Or ($oReceipt.IntOf("fileSize") <> $iFileSize)) Then
ConsoleWrite("Receipt does not match the drive, parent, name, and file; no request sent." & @CRLF)
Exit
EndIf
If ($oReceipt.StringOfEquals("status","complete",True) = True) Then
ConsoleWrite("Already uploaded. Item ID: " & $oReceipt.StringOf("itemId") & @CRLF)
Exit
EndIf
If ($oReceipt.StringOfEquals("status","uploading",True) <> True) Then
ConsoleWrite("Previous session creation is uncertain; inspect the pending receipt before retrying." & @CRLF)
Exit
EndIf
If (($oReceipt.JsonTypeOf("uploadUrl") <> 1) Or ($oReceipt.StringOfEquals("uploadUrl","",True) = True)) Then
ConsoleWrite("Expected a nonempty uploadUrl in the JSON." & @CRLF)
Exit
EndIf
If (($oReceipt.JsonTypeOf("expirationDateTime") <> 1) Or ($oReceipt.StringOfEquals("expirationDateTime","",True) = True)) Then
ConsoleWrite("Expected a nonempty expirationDateTime in the JSON." & @CRLF)
Exit
EndIf
Else
$oEndpoint = ObjCreate("Chilkat.StringBuilder")
$oEndpoint.Append("https://graph.microsoft.com/v1.0/drives/")
$oEndpoint.Append($oHttp.UrlEncode($sDriveId))
$oEndpoint.Append("/items/")
$oEndpoint.Append($oHttp.UrlEncode($sParentId))
$oEndpoint.Append(":/")
$oEndpoint.Append($oHttp.UrlEncode($sFileName))
$oEndpoint.Append(":/createUploadSession")
$oBody = ObjCreate("Chilkat.JsonObject")
$oBody.UpdateString("item.name",$sFileName)
$oBody.UpdateString("item.""@microsoft.graph.conflictBehavior""","fail")
$oReceipt.UpdateString("driveId",$sDriveId)
$oReceipt.UpdateString("parentId",$sParentId)
$oReceipt.UpdateString("name",$sFileName)
$oReceipt.UpdateString("fileHash",$sFileHash)
$oReceipt.UpdateInt("fileSize",$iFileSize)
$oReceipt.UpdateString("status","pending")
$bSuccess = $oReceipt.WriteFile($sReceiptPath)
If ($bSuccess <> True) Then
ConsoleWrite("Could not save the pending receipt; no session created." & @CRLF)
Exit
EndIf
$bSuccess = $oHttp.HttpJson("POST",$oEndpoint.GetAsString(),$oBody,"application/json",$oResp)
If (($bSuccess <> True) And ($oResp.StatusCode = 0)) Then
ConsoleWrite("No HTTP response received; inspect diagnostics privately and reconcile writes before retrying." & @CRLF)
Exit
EndIf
If (($oResp.StatusCode <> 200)) Then
ConsoleWrite("Unexpected HTTP status: " & $oResp.StatusCode & @CRLF)
ConsoleWrite("Request ID: " & $oResp.GetHeaderField("request-id") & @CRLF)
If ($oResp.StatusCode = 429) Then
ConsoleWrite("Retry-After: " & $oResp.GetHeaderField("Retry-After") & @CRLF)
EndIf
Exit
EndIf
$bSuccess = $oResult.Load($oResp.BodyStr)
If ($bSuccess <> True) Then
ConsoleWrite("Expected a well-formed JSON response." & @CRLF)
Exit
EndIf
If (($oResult.JsonTypeOf("uploadUrl") <> 1) Or ($oResult.StringOfEquals("uploadUrl","",True) = True)) Then
ConsoleWrite("Expected a nonempty uploadUrl in the JSON." & @CRLF)
Exit
EndIf
If (($oResult.JsonTypeOf("expirationDateTime") <> 1) Or ($oResult.StringOfEquals("expirationDateTime","",True) = True)) Then
ConsoleWrite("Expected a nonempty expirationDateTime in the JSON." & @CRLF)
Exit
EndIf
$oReceipt.UpdateString("uploadUrl",$oResult.StringOf("uploadUrl"))
$oReceipt.UpdateString("expirationDateTime",$oResult.StringOf("expirationDateTime"))
$oReceipt.UpdateString("status","uploading")
$bSuccess = $oReceipt.WriteFile($sReceiptPath)
If ($bSuccess <> True) Then
ConsoleWrite("Session created but receipt save failed; reconcile before another creation." & @CRLF)
Exit
EndIf
EndIf
Local $sUploadUrl = $oReceipt.StringOf("uploadUrl")
$oServiceUrl = ObjCreate("Chilkat.Url")
$bSuccess = $oServiceUrl.ParseUrl($sUploadUrl)
If ($bSuccess <> True) Then
ConsoleWrite("Invalid returned service URL." & @CRLF)
Exit
EndIf
If (($oServiceUrl.Ssl <> True) Or ($oServiceUrl.Host = "") Or ($oServiceUrl.Login <> "") Or ($oServiceUrl.Password <> "")) Then
ConsoleWrite("Expected an HTTPS service URL without embedded login credentials." & @CRLF)
Exit
EndIf
; Returned URLs can be preauthenticated, Graph-authenticated, or SharePoint-authenticated.
; Never copy Graph authorization to an arbitrary host, and never follow redirects automatically.
$oUploadHttp = ObjCreate("Chilkat.Http")
$oUploadHttp.RequireSslCertVerify = True
$oUploadHttp.FollowRedirects = False
$oUploadHttp.ConnectTimeout = 20
$oUploadHttp.ReadTimeout = 120
$oServiceHost = ObjCreate("Chilkat.StringBuilder")
$oServiceHost.Append($oServiceUrl.Host)
$oServiceQuery = ObjCreate("Chilkat.StringBuilder")
$oServiceQuery.Append($oServiceUrl.Query)
$oAuthMatch = ObjCreate("Chilkat.JsonObject")
Local $iAuthMatched = $oServiceQuery.RegexMatch("(?i)(?:^|[?&])tempauth=[^&]+",$oAuthMatch,100)
If ($iAuthMatched < 0) Then
ConsoleWrite("Could not inspect the service URL query." & @CRLF)
Exit
EndIf
; tempauth carries its own authorization. Do not add a bearer token to that legacy URL.
If ($iAuthMatched = 0) Then
If (($oServiceHost.ContentsEqual("graph.microsoft.com",False) = True) And ($oServiceUrl.Port = 443)) Then
$oUploadHttp.AuthToken = $oToken.StringOf("access_token")
Else
$oTokenFiles = ObjCreate("Chilkat.FileAccess")
If ($oTokenFiles.FileExists("qa_data/tokens/oneDrive-sharepoint.json") = True) Then
$oSharepointToken = ObjCreate("Chilkat.JsonObject")
$oSharepointToken.Strict = True
$bSuccess = $oSharepointToken.LoadFile("qa_data/tokens/oneDrive-sharepoint.json")
If ($bSuccess <> True) Then
ConsoleWrite("Could not read the private SharePoint token cache." & @CRLF)
Exit
EndIf
If (($oSharepointToken.JsonTypeOf("host") <> 1) Or ($oSharepointToken.StringOfEquals("host","",True) = True)) Then
ConsoleWrite("Expected a nonempty host in the JSON." & @CRLF)
Exit
EndIf
If (($oSharepointToken.JsonTypeOf("access_token") <> 1) Or ($oSharepointToken.StringOfEquals("access_token","",True) = True)) Then
ConsoleWrite("Expected a nonempty access_token in the JSON." & @CRLF)
Exit
EndIf
; Configure host independently; never trust a response URL to choose a new credential audience.
If (($oServiceHost.ContentsEqual($oSharepointToken.StringOf("host"),False) = True) And ($oServiceUrl.Port = 443)) Then
$oUploadHttp.AuthToken = $oSharepointToken.StringOf("access_token")
EndIf
EndIf
EndIf
EndIf
; Without a matching token, only a still-valid preauthenticated URL can succeed.
$oExpires = ObjCreate("Chilkat.CkDateTime")
$oNow = ObjCreate("Chilkat.CkDateTime")
$bSuccess = $oExpires.SetFromTimestamp($oReceipt.StringOf("expirationDateTime"))
If ($bSuccess <> True) Then
ConsoleWrite("Invalid session expiry." & @CRLF)
Exit
EndIf
$bSuccess = $oNow.SetFromCurrentSystemTime()
If ($bSuccess <> True) Then
ConsoleWrite("Could not check the expiry." & @CRLF)
Exit
EndIf
If ($oExpires.DiffSeconds($oNow) <= 0) Then
ConsoleWrite("Session expired. Reconcile the destination before creating a replacement." & @CRLF)
Exit
EndIf
; 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.
$oUploadResp = ObjCreate("Chilkat.HttpResponse")
$oSession = ObjCreate("Chilkat.JsonObject")
$oSession.Strict = True
Local $iOffset = 0
If ($bResuming = True) Then
; Server status is authoritative after a lost response; a local offset might be stale.
$bSuccess = $oUploadHttp.HttpNoBody("GET",$sUploadUrl,$oUploadResp)
If (($oUploadResp.StatusCode = 401) Or ($oUploadResp.StatusCode = 403)) Then
ConsoleWrite("Session authentication or permission failure. HTTP status: " & $oUploadResp.StatusCode & @CRLF)
ConsoleWrite("Refresh the correct service token or check grants, then resume this receipt. Do not recreate blindly." & @CRLF)
Exit
EndIf
If (($bSuccess <> True) And ($oUploadResp.StatusCode = 0)) Then
ConsoleWrite("No HTTP response received; inspect diagnostics privately and reconcile writes before retrying." & @CRLF)
Exit
EndIf
If (($oUploadResp.StatusCode <> 200)) Then
ConsoleWrite("Unexpected HTTP status: " & $oUploadResp.StatusCode & @CRLF)
ConsoleWrite("Request ID: " & $oUploadResp.GetHeaderField("request-id") & @CRLF)
If ($oUploadResp.StatusCode = 429) Then
ConsoleWrite("Retry-After: " & $oUploadResp.GetHeaderField("Retry-After") & @CRLF)
EndIf
Exit
EndIf
$bSuccess = $oSession.Load($oUploadResp.BodyStr)
If ($bSuccess <> True) Then
ConsoleWrite("Expected a well-formed JSON response." & @CRLF)
Exit
EndIf
Else
$oSession.UpdateString("nextExpectedRanges[0]","0-")
EndIf
$oRange = ObjCreate("Chilkat.StringBuilder")
$oContentRange = ObjCreate("Chilkat.StringBuilder")
$oOffsetText = ObjCreate("Chilkat.StringBuilder")
$oCountText = ObjCreate("Chilkat.StringBuilder")
$oChunkRequest = ObjCreate("Chilkat.HttpRequest")
$oChunkRequest.HttpVerb = "PUT"
$oChunkRequest.ContentType = "application/octet-stream"
While ($iOffset < $iFileSize)
; This sequential example handles a single open-ended remaining range.
; Stop rather than misinterpreting multiple holes or a bounded range.
If (($oSession.SizeOfArray("nextExpectedRanges") <> 1) Or ($oSession.JsonTypeOf("nextExpectedRanges[0]") <> 1)) Then
ConsoleWrite("Expected one remaining range; inspect session status before continuing." & @CRLF)
Exit
EndIf
$oRange.SetString($oSession.StringOf("nextExpectedRanges[0]"))
$iMatched = $oRange.RegexMatch("\A[0-9]{1,9}-\z",$oMatch,100)
If ($iMatched <> 1) Then
ConsoleWrite("Expected a single open-ended offset such as 3276800-; no more bytes sent." & @CRLF)
Exit
EndIf
Local $iReplacements = $oRange.Replace("-","")
Local $iNextOffset = $oRange.IntValue
If (($iNextOffset < $iOffset) Or ($iNextOffset >= $iFileSize)) Then
ConsoleWrite("Unexpected server offset; retain the receipt and reconcile." & @CRLF)
Exit
EndIf
$iOffset = $iNextOffset
; 10 MiB is 32 * 320 KiB and is below the 60 MiB per-request limit.
Local $iChunkSize = 10485760
If (($iFileSize - $iOffset) < $iChunkSize) Then
$iChunkSize = $iFileSize - $iOffset
EndIf
Local $iEndByte = $iOffset + $iChunkSize - 1
$oOffsetText.Clear
$oOffsetText.AppendInt($iOffset)
$oCountText.Clear
$oCountText.AppendInt($iChunkSize)
$bSuccess = $oChunkRequest.StreamChunkFromFile($sFilePath,$oOffsetText.GetAsString(),$oCountText.GetAsString())
If ($bSuccess <> True) Then
ConsoleWrite("Could not prepare the file chunk." & @CRLF)
Exit
EndIf
$oContentRange.SetString("bytes ")
$oContentRange.AppendInt($iOffset)
$oContentRange.Append("-")
$oContentRange.AppendInt($iEndByte)
$oContentRange.Append("/")
$oContentRange.AppendInt($iFileSize)
$oChunkRequest.AddHeader "Content-Range",$oContentRange.GetAsString()
$bSuccess = $oUploadHttp.HttpReq($sUploadUrl,$oChunkRequest,$oUploadResp)
If (($oUploadResp.StatusCode = 401) Or ($oUploadResp.StatusCode = 403)) Then
ConsoleWrite("Session authentication or permission failure. HTTP status: " & $oUploadResp.StatusCode & @CRLF)
ConsoleWrite("Refresh the correct service token or check grants, then resume this receipt. Do not recreate blindly." & @CRLF)
Exit
EndIf
If (($bSuccess <> True) And ($oUploadResp.StatusCode = 0)) Then
ConsoleWrite("Upload response lost. Retain this receipt and query the session on the next run." & @CRLF)
Exit
EndIf
If (($oUploadResp.StatusCode = 200) Or ($oUploadResp.StatusCode = 201)) Then
If (($iEndByte + 1) <> $iFileSize) Then
ConsoleWrite("Unexpected early completion; reconcile the target." & @CRLF)
Exit
EndIf
$bSuccess = $oResult.Load($oUploadResp.BodyStr)
If ($bSuccess <> True) Then
ConsoleWrite("Upload may have completed but its response is invalid; reconcile before retrying." & @CRLF)
Exit
EndIf
If (($oResult.JsonTypeOf("id") <> 1) Or ($oResult.StringOfEquals("id","",True) = True)) Then
ConsoleWrite("Expected a nonempty id in the JSON." & @CRLF)
Exit
EndIf
$oReceipt.UpdateString("status","complete")
$oReceipt.UpdateString("itemId",$oResult.StringOf("id"))
$bSuccess = $oReceipt.WriteFile($sReceiptPath)
If ($bSuccess <> True) Then
ConsoleWrite("Upload completed but saving its ID failed; reconcile before retrying." & @CRLF)
Exit
EndIf
ConsoleWrite("Upload completed. Item ID: " & $oResult.StringOf("id") & @CRLF)
Exit
EndIf
If (($bSuccess <> True) And ($oUploadResp.StatusCode = 0)) Then
ConsoleWrite("No HTTP response received; inspect diagnostics privately and reconcile writes before retrying." & @CRLF)
Exit
EndIf
If (($oUploadResp.StatusCode <> 202)) Then
ConsoleWrite("Unexpected HTTP status: " & $oUploadResp.StatusCode & @CRLF)
ConsoleWrite("Request ID: " & $oUploadResp.GetHeaderField("request-id") & @CRLF)
If ($oUploadResp.StatusCode = 429) Then
ConsoleWrite("Retry-After: " & $oUploadResp.GetHeaderField("Retry-After") & @CRLF)
EndIf
Exit
EndIf
$bSuccess = $oSession.Load($oUploadResp.BodyStr)
If ($bSuccess <> True) Then
ConsoleWrite("Expected a well-formed JSON response." & @CRLF)
Exit
EndIf
If (($iEndByte + 1) = $iFileSize) Then
ConsoleWrite("Final bytes returned 202, not a completed item. Retain the session and inspect its status." & @CRLF)
Exit
EndIf
$iOffset = $iEndByte + 1
If (($oSession.JsonTypeOf("expirationDateTime") <> 1) Or ($oSession.StringOfEquals("expirationDateTime","",True) = True)) Then
ConsoleWrite("Expected a nonempty expirationDateTime in the JSON." & @CRLF)
Exit
EndIf
$oReceipt.UpdateString("expirationDateTime",$oSession.StringOf("expirationDateTime"))
$oReceipt.UpdateInt("confirmedOffset",$iOffset)
$bSuccess = $oReceipt.WriteFile($sReceiptPath)
If ($bSuccess <> True) Then
ConsoleWrite("Could not checkpoint progress; retain the prior receipt and query the server on resume." & @CRLF)
Exit
EndIf
ConsoleWrite("Uploaded bytes so far: " & $iOffset & @CRLF)
Wend