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 DataFlex Downloads
Use ChilkatAx-win32.pkg
Procedure Test
Boolean iSuccess
Handle hoToken
Handle hoHttp
Variant vResp
Handle hoResp
Handle hoResult
String sDriveId
String sParentId
String sFileName
String sFilePath
String sReceiptPath
Handle hoFac
String sSizeString
Handle hoSizeText
Variant vMatch
Handle hoMatch
Integer iMatched
Integer iFileSize
Handle hoHash
String sFileHash
Handle hoReceipt
Boolean iResuming
Handle hoEndpoint
Variant vBody
Handle hoBody
String sUploadUrl
Handle hoServiceUrl
Handle hoUploadHttp
Handle hoServiceHost
Handle hoServiceQuery
Variant vAuthMatch
Handle hoAuthMatch
Integer iAuthMatched
Handle hoTokenFiles
Handle hoSharepointToken
Handle hoExpires
Variant vNow
Handle hoNow
Variant vUploadResp
Handle hoUploadResp
Handle hoSession
Integer iOffset
Handle hoRange
Handle hoContentRange
Handle hoOffsetText
Handle hoCountText
Variant vChunkRequest
Handle hoChunkRequest
Integer iReplacements
Integer iNextOffset
Integer iChunkSize
Integer iEndByte
String sTemp1
String sTemp2
String sTemp3
Integer iTemp1
Integer iTemp2
Boolean bTemp1
Boolean bTemp2
Boolean bTemp3
Boolean bTemp4
Move False To iSuccess
// Assumes Chilkat is unlocked. See Global Unlock Sample.
Move False To iSuccess
// Obtain a delegated Graph token with this example's file permissions.
// See OneDrive OAuth2 with PKCE.
Get Create (RefClass(cComChilkatJsonObject)) To hoToken
If (Not(IsComObjectCreated(hoToken))) Begin
Send CreateComObject of hoToken
End
Set ComStrict Of hoToken To True
Get ComLoadFile Of hoToken "qa_data/tokens/oneDrive.json" To iSuccess
If (iSuccess <> True) Begin
Showln "Could not load the private OneDrive token cache."
Procedure_Return
End
Get ComJsonTypeOf Of hoToken "access_token" To iTemp1
Get ComStringOfEquals Of hoToken "access_token" "" True To bTemp1
If ((iTemp1 <> 1) Or (bTemp1 = True)) Begin
Showln "Expected a nonempty access_token in the JSON."
Procedure_Return
End
Get Create (RefClass(cComChilkatHttp)) To hoHttp
If (Not(IsComObjectCreated(hoHttp))) Begin
Send CreateComObject of hoHttp
End
Get ComStringOf Of hoToken "access_token" To sTemp1
Set ComAuthToken Of hoHttp To sTemp1
Set ComRequireSslCertVerify Of hoHttp To True
Set ComFollowRedirects Of hoHttp To False
Set ComConnectTimeout Of hoHttp To 20
Set ComReadTimeout Of hoHttp To 120
Send ComSetRequestHeader To hoHttp "Accept" "application/json"
Get Create (RefClass(cComChilkatHttpResponse)) To hoResp
If (Not(IsComObjectCreated(hoResp))) Begin
Send CreateComObject of hoResp
End
Get Create (RefClass(cComChilkatJsonObject)) To hoResult
If (Not(IsComObjectCreated(hoResult))) Begin
Send CreateComObject of hoResult
End
Set ComStrict Of hoResult To True
Move "YOUR_DRIVE_ID" To sDriveId
Move "YOUR_PARENT_FOLDER_ID" To sParentId
Move "large.bin" To sFileName
Move "qa_data/large/sample.bin" To sFilePath
Move "qa_data/oneDrive/upload-session.json" To sReceiptPath
Get Create (RefClass(cComCkFileAccess)) To hoFac
If (Not(IsComObjectCreated(hoFac))) Begin
Send CreateComObject of hoFac
End
Get ComFileSizeStr Of hoFac sFilePath To sSizeString
Get ComLastMethodSuccess Of hoFac To bTemp1
If (bTemp1 <> True) Begin
Showln "Could not determine the source file size."
Procedure_Return
End
Get Create (RefClass(cComChilkatStringBuilder)) To hoSizeText
If (Not(IsComObjectCreated(hoSizeText))) Begin
Send CreateComObject of hoSizeText
End
Get ComAppend Of hoSizeText sSizeString To iSuccess
Get Create (RefClass(cComChilkatJsonObject)) To hoMatch
If (Not(IsComObjectCreated(hoMatch))) Begin
Send CreateComObject of hoMatch
End
Get pvComObject of hoMatch to vMatch
Get ComRegexMatch Of hoSizeText "\A[0-9]{1,9}\z" vMatch 100 To iMatched
If (iMatched <> 1) Begin
Showln "File size exceeds this example's supported range."
Procedure_Return
End
Get ComIntValue Of hoSizeText To iFileSize
If ((iFileSize < 1) Or (iFileSize > 999999999)) Begin
Showln "This example supports nonempty files up to 999,999,999 bytes; its int arithmetic is deliberately bounded."
Procedure_Return
End
Get ComDirEnsureExists Of hoFac "qa_data/oneDrive" To iSuccess
If (iSuccess <> True) Begin
Showln "Could not create the private receipt directory."
Procedure_Return
End
Get Create (RefClass(cComChilkatCrypt2)) To hoHash
If (Not(IsComObjectCreated(hoHash))) Begin
Send CreateComObject of hoHash
End
Set ComHashAlgorithm Of hoHash To "sha256"
Set ComEncodingMode Of hoHash To "hex"
Get ComHashFileENC Of hoHash sFilePath To sFileHash
Get ComLastMethodSuccess Of hoHash To bTemp1
If (bTemp1 <> True) Begin
Showln "Could not fingerprint the source file."
Procedure_Return
End
Get Create (RefClass(cComChilkatJsonObject)) To hoReceipt
If (Not(IsComObjectCreated(hoReceipt))) Begin
Send CreateComObject of hoReceipt
End
Set ComStrict Of hoReceipt To True
Get ComFileExists Of hoFac sReceiptPath To iResuming
If (iResuming = True) Begin
Get ComLoadFile Of hoReceipt sReceiptPath To iSuccess
If (iSuccess <> True) Begin
Showln "Invalid receipt; reconcile the target before another upload."
Procedure_Return
End
Get ComStringOfEquals Of hoReceipt "driveId" sDriveId True To bTemp1
Get ComStringOfEquals Of hoReceipt "parentId" sParentId True To bTemp2
Get ComStringOfEquals Of hoReceipt "name" sFileName True To bTemp3
Get ComStringOfEquals Of hoReceipt "fileHash" sFileHash True To bTemp4
Get ComIntOf Of hoReceipt "fileSize" To iTemp1
If ((bTemp1 <> True) Or (bTemp2 <> True) Or (bTemp3 <> True) Or (bTemp4 <> True) Or (iTemp1 <> iFileSize)) Begin
Showln "Receipt does not match the drive, parent, name, and file; no request sent."
Procedure_Return
End
Get ComStringOfEquals Of hoReceipt "status" "complete" True To bTemp1
If (bTemp1 = True) Begin
Get ComStringOf Of hoReceipt "itemId" To sTemp1
Showln "Already uploaded. Item ID: " sTemp1
Procedure_Return
End
Get ComStringOfEquals Of hoReceipt "status" "uploading" True To bTemp1
If (bTemp1 <> True) Begin
Showln "Previous session creation is uncertain; inspect the pending receipt before retrying."
Procedure_Return
End
Get ComJsonTypeOf Of hoReceipt "uploadUrl" To iTemp1
Get ComStringOfEquals Of hoReceipt "uploadUrl" "" True To bTemp1
If ((iTemp1 <> 1) Or (bTemp1 = True)) Begin
Showln "Expected a nonempty uploadUrl in the JSON."
Procedure_Return
End
Get ComJsonTypeOf Of hoReceipt "expirationDateTime" To iTemp1
Get ComStringOfEquals Of hoReceipt "expirationDateTime" "" True To bTemp1
If ((iTemp1 <> 1) Or (bTemp1 = True)) Begin
Showln "Expected a nonempty expirationDateTime in the JSON."
Procedure_Return
End
End
Else Begin
Get Create (RefClass(cComChilkatStringBuilder)) To hoEndpoint
If (Not(IsComObjectCreated(hoEndpoint))) Begin
Send CreateComObject of hoEndpoint
End
Get ComAppend Of hoEndpoint "https://graph.microsoft.com/v1.0/drives/" To iSuccess
Get ComUrlEncode Of hoHttp sDriveId To sTemp1
Get ComAppend Of hoEndpoint sTemp1 To iSuccess
Get ComAppend Of hoEndpoint "/items/" To iSuccess
Get ComUrlEncode Of hoHttp sParentId To sTemp1
Get ComAppend Of hoEndpoint sTemp1 To iSuccess
Get ComAppend Of hoEndpoint ":/" To iSuccess
Get ComUrlEncode Of hoHttp sFileName To sTemp1
Get ComAppend Of hoEndpoint sTemp1 To iSuccess
Get ComAppend Of hoEndpoint ":/createUploadSession" To iSuccess
Get Create (RefClass(cComChilkatJsonObject)) To hoBody
If (Not(IsComObjectCreated(hoBody))) Begin
Send CreateComObject of hoBody
End
Get ComUpdateString Of hoBody "item.name" sFileName To iSuccess
Get ComUpdateString Of hoBody 'item."@microsoft.graph.conflictBehavior"' "fail" To iSuccess
Get ComUpdateString Of hoReceipt "driveId" sDriveId To iSuccess
Get ComUpdateString Of hoReceipt "parentId" sParentId To iSuccess
Get ComUpdateString Of hoReceipt "name" sFileName To iSuccess
Get ComUpdateString Of hoReceipt "fileHash" sFileHash To iSuccess
Get ComUpdateInt Of hoReceipt "fileSize" iFileSize To iSuccess
Get ComUpdateString Of hoReceipt "status" "pending" To iSuccess
Get ComWriteFile Of hoReceipt sReceiptPath To iSuccess
If (iSuccess <> True) Begin
Showln "Could not save the pending receipt; no session created."
Procedure_Return
End
Get ComGetAsString Of hoEndpoint To sTemp1
Get pvComObject of hoBody to vBody
Get pvComObject of hoResp to vResp
Get ComHttpJson Of hoHttp "POST" sTemp1 vBody "application/json" vResp To iSuccess
Get ComStatusCode Of hoResp To iTemp1
If ((iSuccess <> True) And (iTemp1 = 0)) Begin
Showln "No HTTP response received; inspect diagnostics privately and reconcile writes before retrying."
Procedure_Return
End
Get ComStatusCode Of hoResp To iTemp1
If ((iTemp1 <> 200)) Begin
Get ComStatusCode Of hoResp To iTemp1
Showln "Unexpected HTTP status: " iTemp1
Get ComGetHeaderField Of hoResp "request-id" To sTemp1
Showln "Request ID: " sTemp1
Get ComStatusCode Of hoResp To iTemp1
If (iTemp1 = 429) Begin
Get ComGetHeaderField Of hoResp "Retry-After" To sTemp1
Showln "Retry-After: " sTemp1
End
Procedure_Return
End
Get ComBodyStr Of hoResp To sTemp1
Get ComLoad Of hoResult sTemp1 To iSuccess
If (iSuccess <> True) Begin
Showln "Expected a well-formed JSON response."
Procedure_Return
End
Get ComJsonTypeOf Of hoResult "uploadUrl" To iTemp1
Get ComStringOfEquals Of hoResult "uploadUrl" "" True To bTemp1
If ((iTemp1 <> 1) Or (bTemp1 = True)) Begin
Showln "Expected a nonempty uploadUrl in the JSON."
Procedure_Return
End
Get ComJsonTypeOf Of hoResult "expirationDateTime" To iTemp1
Get ComStringOfEquals Of hoResult "expirationDateTime" "" True To bTemp1
If ((iTemp1 <> 1) Or (bTemp1 = True)) Begin
Showln "Expected a nonempty expirationDateTime in the JSON."
Procedure_Return
End
Get ComStringOf Of hoResult "uploadUrl" To sTemp1
Get ComUpdateString Of hoReceipt "uploadUrl" sTemp1 To iSuccess
Get ComStringOf Of hoResult "expirationDateTime" To sTemp1
Get ComUpdateString Of hoReceipt "expirationDateTime" sTemp1 To iSuccess
Get ComUpdateString Of hoReceipt "status" "uploading" To iSuccess
Get ComWriteFile Of hoReceipt sReceiptPath To iSuccess
If (iSuccess <> True) Begin
Showln "Session created but receipt save failed; reconcile before another creation."
Procedure_Return
End
End
Get ComStringOf Of hoReceipt "uploadUrl" To sUploadUrl
Get Create (RefClass(cComChilkatUrl)) To hoServiceUrl
If (Not(IsComObjectCreated(hoServiceUrl))) Begin
Send CreateComObject of hoServiceUrl
End
Get ComParseUrl Of hoServiceUrl sUploadUrl To iSuccess
If (iSuccess <> True) Begin
Showln "Invalid returned service URL."
Procedure_Return
End
Get ComSsl Of hoServiceUrl To bTemp1
Get ComHost Of hoServiceUrl To sTemp1
Get ComLogin Of hoServiceUrl To sTemp2
Get ComPassword Of hoServiceUrl To sTemp3
If ((bTemp1 <> True) Or (sTemp1 = "") Or (sTemp2 <> "") Or (sTemp3 <> "")) Begin
Showln "Expected an HTTPS service URL without embedded login credentials."
Procedure_Return
End
// Returned URLs can be preauthenticated, Graph-authenticated, or SharePoint-authenticated.
// Never copy Graph authorization to an arbitrary host, and never follow redirects automatically.
Get Create (RefClass(cComChilkatHttp)) To hoUploadHttp
If (Not(IsComObjectCreated(hoUploadHttp))) Begin
Send CreateComObject of hoUploadHttp
End
Set ComRequireSslCertVerify Of hoUploadHttp To True
Set ComFollowRedirects Of hoUploadHttp To False
Set ComConnectTimeout Of hoUploadHttp To 20
Set ComReadTimeout Of hoUploadHttp To 120
Get Create (RefClass(cComChilkatStringBuilder)) To hoServiceHost
If (Not(IsComObjectCreated(hoServiceHost))) Begin
Send CreateComObject of hoServiceHost
End
Get ComHost Of hoServiceUrl To sTemp1
Get ComAppend Of hoServiceHost sTemp1 To iSuccess
Get Create (RefClass(cComChilkatStringBuilder)) To hoServiceQuery
If (Not(IsComObjectCreated(hoServiceQuery))) Begin
Send CreateComObject of hoServiceQuery
End
Get ComQuery Of hoServiceUrl To sTemp1
Get ComAppend Of hoServiceQuery sTemp1 To iSuccess
Get Create (RefClass(cComChilkatJsonObject)) To hoAuthMatch
If (Not(IsComObjectCreated(hoAuthMatch))) Begin
Send CreateComObject of hoAuthMatch
End
Get pvComObject of hoAuthMatch to vAuthMatch
Get ComRegexMatch Of hoServiceQuery "(?i)(?:^|[?&])tempauth=[^&]+" vAuthMatch 100 To iAuthMatched
If (iAuthMatched < 0) Begin
Showln "Could not inspect the service URL query."
Procedure_Return
End
// tempauth carries its own authorization. Do not add a bearer token to that legacy URL.
If (iAuthMatched = 0) Begin
Get ComContentsEqual Of hoServiceHost "graph.microsoft.com" False To bTemp1
Get ComPort Of hoServiceUrl To iTemp1
If ((bTemp1 = True) And (iTemp1 = 443)) Begin
Get ComStringOf Of hoToken "access_token" To sTemp1
Set ComAuthToken Of hoUploadHttp To sTemp1
End
Else Begin
Get Create (RefClass(cComCkFileAccess)) To hoTokenFiles
If (Not(IsComObjectCreated(hoTokenFiles))) Begin
Send CreateComObject of hoTokenFiles
End
Get ComFileExists Of hoTokenFiles "qa_data/tokens/oneDrive-sharepoint.json" To bTemp1
If (bTemp1 = True) Begin
Get Create (RefClass(cComChilkatJsonObject)) To hoSharepointToken
If (Not(IsComObjectCreated(hoSharepointToken))) Begin
Send CreateComObject of hoSharepointToken
End
Set ComStrict Of hoSharepointToken To True
Get ComLoadFile Of hoSharepointToken "qa_data/tokens/oneDrive-sharepoint.json" To iSuccess
If (iSuccess <> True) Begin
Showln "Could not read the private SharePoint token cache."
Procedure_Return
End
Get ComJsonTypeOf Of hoSharepointToken "host" To iTemp1
Get ComStringOfEquals Of hoSharepointToken "host" "" True To bTemp1
If ((iTemp1 <> 1) Or (bTemp1 = True)) Begin
Showln "Expected a nonempty host in the JSON."
Procedure_Return
End
Get ComJsonTypeOf Of hoSharepointToken "access_token" To iTemp1
Get ComStringOfEquals Of hoSharepointToken "access_token" "" True To bTemp1
If ((iTemp1 <> 1) Or (bTemp1 = True)) Begin
Showln "Expected a nonempty access_token in the JSON."
Procedure_Return
End
// Configure host independently; never trust a response URL to choose a new credential audience.
Get ComContentsEqual Of hoServiceHost (ComStringOf(hoSharepointToken, "host")) False To bTemp1
Get ComPort Of hoServiceUrl To iTemp1
If ((bTemp1 = True) And (iTemp1 = 443)) Begin
Get ComStringOf Of hoSharepointToken "access_token" To sTemp1
Set ComAuthToken Of hoUploadHttp To sTemp1
End
End
End
End
// Without a matching token, only a still-valid preauthenticated URL can succeed.
Get Create (RefClass(cComCkDateTime)) To hoExpires
If (Not(IsComObjectCreated(hoExpires))) Begin
Send CreateComObject of hoExpires
End
Get Create (RefClass(cComCkDateTime)) To hoNow
If (Not(IsComObjectCreated(hoNow))) Begin
Send CreateComObject of hoNow
End
Get ComStringOf Of hoReceipt "expirationDateTime" To sTemp1
Get ComSetFromTimestamp Of hoExpires sTemp1 To iSuccess
If (iSuccess <> True) Begin
Showln "Invalid session expiry."
Procedure_Return
End
Get ComSetFromCurrentSystemTime Of hoNow To iSuccess
If (iSuccess <> True) Begin
Showln "Could not check the expiry."
Procedure_Return
End
Get ComDiffSeconds Of hoExpires Get pvComObject of hoNow to vNow
vNow To iTemp1
If (iTemp1 <= 0) Begin
Showln "Session expired. Reconcile the destination before creating a replacement."
Procedure_Return
End
// 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.
Get Create (RefClass(cComChilkatHttpResponse)) To hoUploadResp
If (Not(IsComObjectCreated(hoUploadResp))) Begin
Send CreateComObject of hoUploadResp
End
Get Create (RefClass(cComChilkatJsonObject)) To hoSession
If (Not(IsComObjectCreated(hoSession))) Begin
Send CreateComObject of hoSession
End
Set ComStrict Of hoSession To True
Move 0 To iOffset
If (iResuming = True) Begin
// Server status is authoritative after a lost response; a local offset might be stale.
Get pvComObject of hoUploadResp to vUploadResp
Get ComHttpNoBody Of hoUploadHttp "GET" sUploadUrl vUploadResp To iSuccess
Get ComStatusCode Of hoUploadResp To iTemp1
Get ComStatusCode Of hoUploadResp To iTemp2
If ((iTemp1 = 401) Or (iTemp2 = 403)) Begin
Get ComStatusCode Of hoUploadResp To iTemp1
Showln "Session authentication or permission failure. HTTP status: " iTemp1
Showln "Refresh the correct service token or check grants, then resume this receipt. Do not recreate blindly."
Procedure_Return
End
Get ComStatusCode Of hoUploadResp To iTemp1
If ((iSuccess <> True) And (iTemp1 = 0)) Begin
Showln "No HTTP response received; inspect diagnostics privately and reconcile writes before retrying."
Procedure_Return
End
Get ComStatusCode Of hoUploadResp To iTemp1
If ((iTemp1 <> 200)) Begin
Get ComStatusCode Of hoUploadResp To iTemp1
Showln "Unexpected HTTP status: " iTemp1
Get ComGetHeaderField Of hoUploadResp "request-id" To sTemp1
Showln "Request ID: " sTemp1
Get ComStatusCode Of hoUploadResp To iTemp1
If (iTemp1 = 429) Begin
Get ComGetHeaderField Of hoUploadResp "Retry-After" To sTemp1
Showln "Retry-After: " sTemp1
End
Procedure_Return
End
Get ComBodyStr Of hoUploadResp To sTemp1
Get ComLoad Of hoSession sTemp1 To iSuccess
If (iSuccess <> True) Begin
Showln "Expected a well-formed JSON response."
Procedure_Return
End
End
Else Begin
Get ComUpdateString Of hoSession "nextExpectedRanges[0]" "0-" To iSuccess
End
Get Create (RefClass(cComChilkatStringBuilder)) To hoRange
If (Not(IsComObjectCreated(hoRange))) Begin
Send CreateComObject of hoRange
End
Get Create (RefClass(cComChilkatStringBuilder)) To hoContentRange
If (Not(IsComObjectCreated(hoContentRange))) Begin
Send CreateComObject of hoContentRange
End
Get Create (RefClass(cComChilkatStringBuilder)) To hoOffsetText
If (Not(IsComObjectCreated(hoOffsetText))) Begin
Send CreateComObject of hoOffsetText
End
Get Create (RefClass(cComChilkatStringBuilder)) To hoCountText
If (Not(IsComObjectCreated(hoCountText))) Begin
Send CreateComObject of hoCountText
End
Get Create (RefClass(cComChilkatHttpRequest)) To hoChunkRequest
If (Not(IsComObjectCreated(hoChunkRequest))) Begin
Send CreateComObject of hoChunkRequest
End
Set ComHttpVerb Of hoChunkRequest To "PUT"
Set ComContentType Of hoChunkRequest To "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.
Get ComSizeOfArray Of hoSession "nextExpectedRanges" To iTemp1
Get ComJsonTypeOf Of hoSession "nextExpectedRanges[0]" To iTemp2
If ((iTemp1 <> 1) Or (iTemp2 <> 1)) Begin
Showln "Expected one remaining range; inspect session status before continuing."
Procedure_Return
End
Get ComStringOf Of hoSession "nextExpectedRanges[0]" To sTemp1
Get ComSetString Of hoRange sTemp1 To iSuccess
Get pvComObject of hoMatch to vMatch
Get ComRegexMatch Of hoRange "\A[0-9]{1,9}-\z" vMatch 100 To iMatched
If (iMatched <> 1) Begin
Showln "Expected a single open-ended offset such as 3276800-; no more bytes sent."
Procedure_Return
End
Get ComReplace Of hoRange "-" "" To iReplacements
Get ComIntValue Of hoRange To iNextOffset
If ((iNextOffset < iOffset) Or (iNextOffset >= iFileSize)) Begin
Showln "Unexpected server offset; retain the receipt and reconcile."
Procedure_Return
End
Move iNextOffset To iOffset
// 10 MiB is 32 * 320 KiB and is below the 60 MiB per-request limit.
Move 10485760 To iChunkSize
If ((iFileSize - iOffset) < iChunkSize) Begin
Move (iFileSize - iOffset) To iChunkSize
End
Move (iOffset + iChunkSize - 1) To iEndByte
Send ComClear To hoOffsetText
Get ComAppendInt Of hoOffsetText iOffset To iSuccess
Send ComClear To hoCountText
Get ComAppendInt Of hoCountText iChunkSize To iSuccess
Get ComGetAsString Of hoOffsetText To sTemp1
Get ComGetAsString Of hoCountText To sTemp2
Get ComStreamChunkFromFile Of hoChunkRequest sFilePath sTemp1 sTemp2 To iSuccess
If (iSuccess <> True) Begin
Showln "Could not prepare the file chunk."
Procedure_Return
End
Get ComSetString Of hoContentRange "bytes " To iSuccess
Get ComAppendInt Of hoContentRange iOffset To iSuccess
Get ComAppend Of hoContentRange "-" To iSuccess
Get ComAppendInt Of hoContentRange iEndByte To iSuccess
Get ComAppend Of hoContentRange "/" To iSuccess
Get ComAppendInt Of hoContentRange iFileSize To iSuccess
Get ComGetAsString Of hoContentRange To sTemp1
Send ComAddHeader To hoChunkRequest "Content-Range" sTemp1
Get pvComObject of hoChunkRequest to vChunkRequest
Get pvComObject of hoUploadResp to vUploadResp
Get ComHttpReq Of hoUploadHttp sUploadUrl vChunkRequest vUploadResp To iSuccess
Get ComStatusCode Of hoUploadResp To iTemp1
Get ComStatusCode Of hoUploadResp To iTemp2
If ((iTemp1 = 401) Or (iTemp2 = 403)) Begin
Get ComStatusCode Of hoUploadResp To iTemp1
Showln "Session authentication or permission failure. HTTP status: " iTemp1
Showln "Refresh the correct service token or check grants, then resume this receipt. Do not recreate blindly."
Procedure_Return
End
Get ComStatusCode Of hoUploadResp To iTemp1
If ((iSuccess <> True) And (iTemp1 = 0)) Begin
Showln "Upload response lost. Retain this receipt and query the session on the next run."
Procedure_Return
End
Get ComStatusCode Of hoUploadResp To iTemp1
Get ComStatusCode Of hoUploadResp To iTemp2
If ((iTemp1 = 200) Or (iTemp2 = 201)) Begin
If ((iEndByte + 1) <> iFileSize) Begin
Showln "Unexpected early completion; reconcile the target."
Procedure_Return
End
Get ComBodyStr Of hoUploadResp To sTemp1
Get ComLoad Of hoResult sTemp1 To iSuccess
If (iSuccess <> True) Begin
Showln "Upload may have completed but its response is invalid; reconcile before retrying."
Procedure_Return
End
Get ComJsonTypeOf Of hoResult "id" To iTemp1
Get ComStringOfEquals Of hoResult "id" "" True To bTemp1
If ((iTemp1 <> 1) Or (bTemp1 = True)) Begin
Showln "Expected a nonempty id in the JSON."
Procedure_Return
End
Get ComUpdateString Of hoReceipt "status" "complete" To iSuccess
Get ComStringOf Of hoResult "id" To sTemp1
Get ComUpdateString Of hoReceipt "itemId" sTemp1 To iSuccess
Get ComWriteFile Of hoReceipt sReceiptPath To iSuccess
If (iSuccess <> True) Begin
Showln "Upload completed but saving its ID failed; reconcile before retrying."
Procedure_Return
End
Get ComStringOf Of hoResult "id" To sTemp1
Showln "Upload completed. Item ID: " sTemp1
Procedure_Return
End
Get ComStatusCode Of hoUploadResp To iTemp1
If ((iSuccess <> True) And (iTemp1 = 0)) Begin
Showln "No HTTP response received; inspect diagnostics privately and reconcile writes before retrying."
Procedure_Return
End
Get ComStatusCode Of hoUploadResp To iTemp1
If ((iTemp1 <> 202)) Begin
Get ComStatusCode Of hoUploadResp To iTemp1
Showln "Unexpected HTTP status: " iTemp1
Get ComGetHeaderField Of hoUploadResp "request-id" To sTemp1
Showln "Request ID: " sTemp1
Get ComStatusCode Of hoUploadResp To iTemp1
If (iTemp1 = 429) Begin
Get ComGetHeaderField Of hoUploadResp "Retry-After" To sTemp1
Showln "Retry-After: " sTemp1
End
Procedure_Return
End
Get ComBodyStr Of hoUploadResp To sTemp1
Get ComLoad Of hoSession sTemp1 To iSuccess
If (iSuccess <> True) Begin
Showln "Expected a well-formed JSON response."
Procedure_Return
End
If ((iEndByte + 1) = iFileSize) Begin
Showln "Final bytes returned 202, not a completed item. Retain the session and inspect its status."
Procedure_Return
End
Move (iEndByte + 1) To iOffset
Get ComJsonTypeOf Of hoSession "expirationDateTime" To iTemp1
Get ComStringOfEquals Of hoSession "expirationDateTime" "" True To bTemp1
If ((iTemp1 <> 1) Or (bTemp1 = True)) Begin
Showln "Expected a nonempty expirationDateTime in the JSON."
Procedure_Return
End
Get ComStringOf Of hoSession "expirationDateTime" To sTemp1
Get ComUpdateString Of hoReceipt "expirationDateTime" sTemp1 To iSuccess
Get ComUpdateInt Of hoReceipt "confirmedOffset" iOffset To iSuccess
Get ComWriteFile Of hoReceipt sReceiptPath To iSuccess
If (iSuccess <> True) Begin
Showln "Could not checkpoint progress; retain the prior receipt and query the server on resume."
Procedure_Return
End
Showln "Uploaded bytes so far: " iOffset
Loop
End_Procedure