Sample code for 30+ languages & platforms
Ruby 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 Ruby Downloads

Ruby
require 'chilkat'

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.
token = Chilkat::CkJsonObject.new()
token.put_Strict(true)
success = token.LoadFile("qa_data/tokens/oneDrive.json")
if (success != true)
    print "Could not load the private OneDrive token cache." + "\n";
    exit
end

if ((token.JsonTypeOf("access_token") != 1) or (token.StringOfEquals("access_token","",true) == true))
    print "Expected a nonempty access_token in the JSON." + "\n";
    exit
end

http = Chilkat::CkHttp.new()
http.put_AuthToken(token.stringOf("access_token"))
http.put_RequireSslCertVerify(true)
http.put_FollowRedirects(false)
http.put_ConnectTimeout(20)
http.put_ReadTimeout(120)
http.SetRequestHeader("Accept","application/json")
resp = Chilkat::CkHttpResponse.new()
result = Chilkat::CkJsonObject.new()
result.put_Strict(true)
driveId = "YOUR_DRIVE_ID"
parentId = "YOUR_PARENT_FOLDER_ID"
fileName = "large.bin"
filePath = "qa_data/large/sample.bin"
receiptPath = "qa_data/oneDrive/upload-session.json"
fac = Chilkat::CkFileAccess.new()
sizeString = fac.fileSizeStr(filePath)
if (fac.get_LastMethodSuccess() != true)
    print "Could not determine the source file size." + "\n";
    exit
end

sizeText = Chilkat::CkStringBuilder.new()
sizeText.Append(sizeString)
match = Chilkat::CkJsonObject.new()
matched = sizeText.RegexMatch("\\A[0-9]{1,9}\\z",match,100)
if (matched != 1)
    print "File size exceeds this example's supported range." + "\n";
    exit
end

fileSize = sizeText.get_IntValue()
if ((fileSize < 1) or (fileSize > 999999999))
    print "This example supports nonempty files up to 999,999,999 bytes; its int arithmetic is deliberately bounded." + "\n";
    exit
end

success = fac.DirEnsureExists("qa_data/oneDrive")
if (success != true)
    print "Could not create the private receipt directory." + "\n";
    exit
end

hash = Chilkat::CkCrypt2.new()
hash.put_HashAlgorithm("sha256")
hash.put_EncodingMode("hex")
fileHash = hash.hashFileENC(filePath)
if (hash.get_LastMethodSuccess() != true)
    print "Could not fingerprint the source file." + "\n";
    exit
end

receipt = Chilkat::CkJsonObject.new()
receipt.put_Strict(true)
resuming = fac.FileExists(receiptPath)
if (resuming == true)
    success = receipt.LoadFile(receiptPath)
    if (success != true)
        print "Invalid receipt; reconcile the target before another upload." + "\n";
        exit
    end

    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))
        print "Receipt does not match the drive, parent, name, and file; no request sent." + "\n";
        exit
    end

    if (receipt.StringOfEquals("status","complete",true) == true)
        print "Already uploaded. Item ID: " + receipt.stringOf("itemId") + "\n";
        exit
    end

    if (receipt.StringOfEquals("status","uploading",true) != true)
        print "Previous session creation is uncertain; inspect the pending receipt before retrying." + "\n";
        exit
    end

    if ((receipt.JsonTypeOf("uploadUrl") != 1) or (receipt.StringOfEquals("uploadUrl","",true) == true))
        print "Expected a nonempty uploadUrl in the JSON." + "\n";
        exit
    end

    if ((receipt.JsonTypeOf("expirationDateTime") != 1) or (receipt.StringOfEquals("expirationDateTime","",true) == true))
        print "Expected a nonempty expirationDateTime in the JSON." + "\n";
        exit
    end

else
    endpoint = Chilkat::CkStringBuilder.new()
    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")
    body = Chilkat::CkJsonObject.new()
    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)
        print "Could not save the pending receipt; no session created." + "\n";
        exit
    end

    success = http.HttpJson("POST",endpoint.getAsString(),body,"application/json",resp)
    if ((success != true) and (resp.get_StatusCode() == 0))
        print "No HTTP response received; inspect diagnostics privately and reconcile writes before retrying." + "\n";
        exit
    end

    if ((resp.get_StatusCode() != 200))
        print "Unexpected HTTP status: " + resp.get_StatusCode().to_s() + "\n";
        print "Request ID: " + resp.getHeaderField("request-id") + "\n";
        if (resp.get_StatusCode() == 429)
            print "Retry-After: " + resp.getHeaderField("Retry-After") + "\n";
        end

        exit
    end

    success = result.Load(resp.bodyStr())
    if (success != true)
        print "Expected a well-formed JSON response." + "\n";
        exit
    end

    if ((result.JsonTypeOf("uploadUrl") != 1) or (result.StringOfEquals("uploadUrl","",true) == true))
        print "Expected a nonempty uploadUrl in the JSON." + "\n";
        exit
    end

    if ((result.JsonTypeOf("expirationDateTime") != 1) or (result.StringOfEquals("expirationDateTime","",true) == true))
        print "Expected a nonempty expirationDateTime in the JSON." + "\n";
        exit
    end

    receipt.UpdateString("uploadUrl",result.stringOf("uploadUrl"))
    receipt.UpdateString("expirationDateTime",result.stringOf("expirationDateTime"))
    receipt.UpdateString("status","uploading")
    success = receipt.WriteFile(receiptPath)
    if (success != true)
        print "Session created but receipt save failed; reconcile before another creation." + "\n";
        exit
    end

end

uploadUrl = receipt.stringOf("uploadUrl")
serviceUrl = Chilkat::CkUrl.new()
success = serviceUrl.ParseUrl(uploadUrl)
if (success != true)
    print "Invalid returned service URL." + "\n";
    exit
end

if ((serviceUrl.get_Ssl() != true) or (serviceUrl.host() == "") or (serviceUrl.login() != "") or (serviceUrl.password() != ""))
    print "Expected an HTTPS service URL without embedded login credentials." + "\n";
    exit
end

#  Returned URLs can be preauthenticated, Graph-authenticated, or SharePoint-authenticated.
#  Never copy Graph authorization to an arbitrary host, and never follow redirects automatically.
uploadHttp = Chilkat::CkHttp.new()
uploadHttp.put_RequireSslCertVerify(true)
uploadHttp.put_FollowRedirects(false)
uploadHttp.put_ConnectTimeout(20)
uploadHttp.put_ReadTimeout(120)
serviceHost = Chilkat::CkStringBuilder.new()
serviceHost.Append(serviceUrl.host())
serviceQuery = Chilkat::CkStringBuilder.new()
serviceQuery.Append(serviceUrl.query())
authMatch = Chilkat::CkJsonObject.new()
authMatched = serviceQuery.RegexMatch("(?i)(?:^|[?&])tempauth=[^&]+",authMatch,100)
if (authMatched < 0)
    print "Could not inspect the service URL query." + "\n";
    exit
end

#  tempauth carries its own authorization. Do not add a bearer token to that legacy URL.
if (authMatched == 0)
    if ((serviceHost.ContentsEqual("graph.microsoft.com",false) == true) and (serviceUrl.get_Port() == 443))
        uploadHttp.put_AuthToken(token.stringOf("access_token"))
    else
        tokenFiles = Chilkat::CkFileAccess.new()
        if (tokenFiles.FileExists("qa_data/tokens/oneDrive-sharepoint.json") == true)
            sharepointToken = Chilkat::CkJsonObject.new()
            sharepointToken.put_Strict(true)
            success = sharepointToken.LoadFile("qa_data/tokens/oneDrive-sharepoint.json")
            if (success != true)
                print "Could not read the private SharePoint token cache." + "\n";
                exit
            end

            if ((sharepointToken.JsonTypeOf("host") != 1) or (sharepointToken.StringOfEquals("host","",true) == true))
                print "Expected a nonempty host in the JSON." + "\n";
                exit
            end

            if ((sharepointToken.JsonTypeOf("access_token") != 1) or (sharepointToken.StringOfEquals("access_token","",true) == true))
                print "Expected a nonempty access_token in the JSON." + "\n";
                exit
            end

            #  Configure host independently; never trust a response URL to choose a new credential audience.
            if ((serviceHost.ContentsEqual(sharepointToken.stringOf("host"),false) == true) and (serviceUrl.get_Port() == 443))
                uploadHttp.put_AuthToken(sharepointToken.stringOf("access_token"))
            end

        end

    end

end

#  Without a matching token, only a still-valid preauthenticated URL can succeed.
expires = Chilkat::CkDateTime.new()
now = Chilkat::CkDateTime.new()
success = expires.SetFromTimestamp(receipt.stringOf("expirationDateTime"))
if (success != true)
    print "Invalid session expiry." + "\n";
    exit
end

success = now.SetFromCurrentSystemTime()
if (success != true)
    print "Could not check the expiry." + "\n";
    exit
end

if (expires.DiffSeconds(now) <= 0)
    print "Session expired. Reconcile the destination before creating a replacement." + "\n";
    exit
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.
uploadResp = Chilkat::CkHttpResponse.new()
session = Chilkat::CkJsonObject.new()
session.put_Strict(true)
offset = 0
if (resuming == true)
    #  Server status is authoritative after a lost response; a local offset might be stale.
    success = uploadHttp.HttpNoBody("GET",uploadUrl,uploadResp)
    if ((uploadResp.get_StatusCode() == 401) or (uploadResp.get_StatusCode() == 403))
        print "Session authentication or permission failure. HTTP status: " + uploadResp.get_StatusCode().to_s() + "\n";
        print "Refresh the correct service token or check grants, then resume this receipt. Do not recreate blindly." + "\n";
        exit
    end

    if ((success != true) and (uploadResp.get_StatusCode() == 0))
        print "No HTTP response received; inspect diagnostics privately and reconcile writes before retrying." + "\n";
        exit
    end

    if ((uploadResp.get_StatusCode() != 200))
        print "Unexpected HTTP status: " + uploadResp.get_StatusCode().to_s() + "\n";
        print "Request ID: " + uploadResp.getHeaderField("request-id") + "\n";
        if (uploadResp.get_StatusCode() == 429)
            print "Retry-After: " + uploadResp.getHeaderField("Retry-After") + "\n";
        end

        exit
    end

    success = session.Load(uploadResp.bodyStr())
    if (success != true)
        print "Expected a well-formed JSON response." + "\n";
        exit
    end

else
    session.UpdateString("nextExpectedRanges[0]","0-")
end

range = Chilkat::CkStringBuilder.new()
contentRange = Chilkat::CkStringBuilder.new()
offsetText = Chilkat::CkStringBuilder.new()
countText = Chilkat::CkStringBuilder.new()
chunkRequest = Chilkat::CkHttpRequest.new()
chunkRequest.put_HttpVerb("PUT")
chunkRequest.put_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))
        print "Expected one remaining range; inspect session status before continuing." + "\n";
        exit
    end

    range.SetString(session.stringOf("nextExpectedRanges[0]"))
    matched = range.RegexMatch("\\A[0-9]{1,9}-\\z",match,100)
    if (matched != 1)
        print "Expected a single open-ended offset such as 3276800-; no more bytes sent." + "\n";
        exit
    end

    replacements = range.Replace("-","")
    nextOffset = range.get_IntValue()
    if ((nextOffset < offset) or (nextOffset >= fileSize))
        print "Unexpected server offset; retain the receipt and reconcile." + "\n";
        exit
    end

    offset = nextOffset
    #  10 MiB is 32 * 320 KiB and is below the 60 MiB per-request limit.
    chunkSize = 10485760
    if ((fileSize - offset) < chunkSize)
        chunkSize = fileSize - offset
    end

    endByte = offset + chunkSize - 1
    offsetText.Clear()
    offsetText.AppendInt(offset)
    countText.Clear()
    countText.AppendInt(chunkSize)
    success = chunkRequest.StreamChunkFromFile(filePath,offsetText.getAsString(),countText.getAsString())
    if (success != true)
        print "Could not prepare the file chunk." + "\n";
        exit
    end

    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.get_StatusCode() == 401) or (uploadResp.get_StatusCode() == 403))
        print "Session authentication or permission failure. HTTP status: " + uploadResp.get_StatusCode().to_s() + "\n";
        print "Refresh the correct service token or check grants, then resume this receipt. Do not recreate blindly." + "\n";
        exit
    end

    if ((success != true) and (uploadResp.get_StatusCode() == 0))
        print "Upload response lost. Retain this receipt and query the session on the next run." + "\n";
        exit
    end

    if ((uploadResp.get_StatusCode() == 200) or (uploadResp.get_StatusCode() == 201))
        if ((endByte + 1) != fileSize)
            print "Unexpected early completion; reconcile the target." + "\n";
            exit
        end

        success = result.Load(uploadResp.bodyStr())
        if (success != true)
            print "Upload may have completed but its response is invalid; reconcile before retrying." + "\n";
            exit
        end

        if ((result.JsonTypeOf("id") != 1) or (result.StringOfEquals("id","",true) == true))
            print "Expected a nonempty id in the JSON." + "\n";
            exit
        end

        receipt.UpdateString("status","complete")
        receipt.UpdateString("itemId",result.stringOf("id"))
        success = receipt.WriteFile(receiptPath)
        if (success != true)
            print "Upload completed but saving its ID failed; reconcile before retrying." + "\n";
            exit
        end

        print "Upload completed. Item ID: " + result.stringOf("id") + "\n";
        exit
    end

    if ((success != true) and (uploadResp.get_StatusCode() == 0))
        print "No HTTP response received; inspect diagnostics privately and reconcile writes before retrying." + "\n";
        exit
    end

    if ((uploadResp.get_StatusCode() != 202))
        print "Unexpected HTTP status: " + uploadResp.get_StatusCode().to_s() + "\n";
        print "Request ID: " + uploadResp.getHeaderField("request-id") + "\n";
        if (uploadResp.get_StatusCode() == 429)
            print "Retry-After: " + uploadResp.getHeaderField("Retry-After") + "\n";
        end

        exit
    end

    success = session.Load(uploadResp.bodyStr())
    if (success != true)
        print "Expected a well-formed JSON response." + "\n";
        exit
    end

    if ((endByte + 1) == fileSize)
        print "Final bytes returned 202, not a completed item. Retain the session and inspect its status." + "\n";
        exit
    end

    offset = endByte + 1
    if ((session.JsonTypeOf("expirationDateTime") != 1) or (session.StringOfEquals("expirationDateTime","",true) == true))
        print "Expected a nonempty expirationDateTime in the JSON." + "\n";
        exit
    end

    receipt.UpdateString("expirationDateTime",session.stringOf("expirationDateTime"))
    receipt.UpdateInt("confirmedOffset",offset)
    success = receipt.WriteFile(receiptPath)
    if (success != true)
        print "Could not checkpoint progress; retain the prior receipt and query the server on resume." + "\n";
        exit
    end

    print "Uploaded bytes so far: " + offset.to_s() + "\n";
end