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

Lua
local chilkat = require("chilkat")

-- Assumes Chilkat is unlocked. See Global Unlock Sample.
local success = false
-- Obtain a delegated Graph token with this example's file permissions.
-- See OneDrive OAuth2 with PKCE.
local token = chilkat.JsonObject.new()
token.strict = true
success = token:load_file("qa_data/tokens/oneDrive.json")
if not success then
    print("Could not load the private OneDrive token cache.")
    return
end

if (token:json_type_of("access_token") ~= 1) or (token:string_of_equals("access_token", "", true)) then
    print("Expected a nonempty access_token in the JSON.")
    return
end

local http = chilkat.Http.new()
http.auth_token = token:string_of("access_token")
http.require_ssl_cert_verify = true
http.follow_redirects = false
http.connect_timeout = 20
http.read_timeout = 120
http:set_request_header("Accept", "application/json")
local resp = chilkat.HttpResponse.new()
local result = chilkat.JsonObject.new()
result.strict = true
local driveId = "YOUR_DRIVE_ID"
local parentId = "YOUR_PARENT_FOLDER_ID"
local fileName = "large.bin"
local filePath = "qa_data/large/sample.bin"
local receiptPath = "qa_data/oneDrive/upload-session.json"
local fac = chilkat.FileAccess.new()
local sizeString = fac:file_size_str(filePath)
if not fac.last_method_success then
    print("Could not determine the source file size.")
    return
end

local sizeText = chilkat.StringBuilder.new()
sizeText:append(sizeString)
local match = chilkat.JsonObject.new()
local matched = sizeText:regex_match("\\A[0-9]{1,9}\\z", match, 100)
if matched ~= 1 then
    print("File size exceeds this example's supported range.")
    return
end

local fileSize = sizeText.int_value
if (fileSize < 1) or (fileSize > 999999999) then
    print("This example supports nonempty files up to 999,999,999 bytes; its int arithmetic is deliberately bounded.")
    return
end

success = fac:dir_ensure_exists("qa_data/oneDrive")
if not success then
    print("Could not create the private receipt directory.")
    return
end

local hash = chilkat.Crypt2.new()
hash.hash_algorithm = "sha256"
hash.encoding_mode = "hex"
local fileHash = hash:hash_file_enc(filePath)
if not hash.last_method_success then
    print("Could not fingerprint the source file.")
    return
end

local receipt = chilkat.JsonObject.new()
receipt.strict = true
local resuming = fac:file_exists(receiptPath)
if resuming then
    success = receipt:load_file(receiptPath)
    if not success then
        print("Invalid receipt; reconcile the target before another upload.")
        return
    end

    if (not receipt:string_of_equals("driveId", driveId, true)) or ((not receipt:string_of_equals("parentId", parentId, true)) or ((not receipt:string_of_equals("name", fileName, true)) or ((not receipt:string_of_equals("fileHash", fileHash, true)) or (receipt:int_of("fileSize") ~= fileSize)))) then
        print("Receipt does not match the drive, parent, name, and file; no request sent.")
        return
    end

    if receipt:string_of_equals("status", "complete", true) then
        print("Already uploaded. Item ID: " .. receipt:string_of("itemId"))
        return
    end

    if not receipt:string_of_equals("status", "uploading", true) then
        print("Previous session creation is uncertain; inspect the pending receipt before retrying.")
        return
    end

    if (receipt:json_type_of("uploadUrl") ~= 1) or (receipt:string_of_equals("uploadUrl", "", true)) then
        print("Expected a nonempty uploadUrl in the JSON.")
        return
    end

    if (receipt:json_type_of("expirationDateTime") ~= 1) or (receipt:string_of_equals("expirationDateTime", "", true)) then
        print("Expected a nonempty expirationDateTime in the JSON.")
        return
    end
else
    local endpoint = chilkat.StringBuilder.new()
    endpoint:append("https://graph.microsoft.com/v1.0/drives/")
    endpoint:append(http:url_encode(driveId))
    endpoint:append("/items/")
    endpoint:append(http:url_encode(parentId))
    endpoint:append(":/")
    endpoint:append(http:url_encode(fileName))
    endpoint:append(":/createUploadSession")
    local body = chilkat.JsonObject.new()
    body:update_string("item.name", fileName)
    body:update_string("item.\"@microsoft.graph.conflictBehavior\"", "fail")
    receipt:update_string("driveId", driveId)
    receipt:update_string("parentId", parentId)
    receipt:update_string("name", fileName)
    receipt:update_string("fileHash", fileHash)
    receipt:update_int("fileSize", fileSize)
    receipt:update_string("status", "pending")
    success = receipt:write_file(receiptPath)
    if not success then
        print("Could not save the pending receipt; no session created.")
        return
    end

    success = http:http_json("POST", endpoint:get_as_string(), body, "application/json", resp)
    if (not success) and (resp.status_code == 0) then
        print("No HTTP response received; inspect diagnostics privately and reconcile writes before retrying.")
        return
    end

    if resp.status_code ~= 200 then
        print("Unexpected HTTP status: " .. resp.status_code)
        print("Request ID: " .. resp:get_header_field("request-id"))
        if resp.status_code == 429 then
            print("Retry-After: " .. resp:get_header_field("Retry-After"))
        end

        return
    end

    success = result:load(resp.body_str)
    if not success then
        print("Expected a well-formed JSON response.")
        return
    end

    if (result:json_type_of("uploadUrl") ~= 1) or (result:string_of_equals("uploadUrl", "", true)) then
        print("Expected a nonempty uploadUrl in the JSON.")
        return
    end

    if (result:json_type_of("expirationDateTime") ~= 1) or (result:string_of_equals("expirationDateTime", "", true)) then
        print("Expected a nonempty expirationDateTime in the JSON.")
        return
    end

    receipt:update_string("uploadUrl", result:string_of("uploadUrl"))
    receipt:update_string("expirationDateTime", result:string_of("expirationDateTime"))
    receipt:update_string("status", "uploading")
    success = receipt:write_file(receiptPath)
    if not success then
        print("Session created but receipt save failed; reconcile before another creation.")
        return
    end
end

local uploadUrl = receipt:string_of("uploadUrl")
local serviceUrl = chilkat.Url.new()
success = serviceUrl:parse_url(uploadUrl)
if not success then
    print("Invalid returned service URL.")
    return
end

if (not serviceUrl.ssl) or ((serviceUrl.host == "") or ((serviceUrl.login ~= "") or (serviceUrl.password ~= ""))) then
    print("Expected an HTTPS service URL without embedded login credentials.")
    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.
local uploadHttp = chilkat.Http.new()
uploadHttp.require_ssl_cert_verify = true
uploadHttp.follow_redirects = false
uploadHttp.connect_timeout = 20
uploadHttp.read_timeout = 120
local serviceHost = chilkat.StringBuilder.new()
serviceHost:append(serviceUrl.host)
local serviceQuery = chilkat.StringBuilder.new()
serviceQuery:append(serviceUrl.query)
local authMatch = chilkat.JsonObject.new()
local authMatched = serviceQuery:regex_match("(?i)(?:^|[?&])tempauth=[^&]+", authMatch, 100)
if authMatched < 0 then
    print("Could not inspect the service URL query.")
    return
end

-- tempauth carries its own authorization. Do not add a bearer token to that legacy URL.
if authMatched == 0 then
    if (serviceHost:contents_equal("graph.microsoft.com", false)) and (serviceUrl.port == 443) then
        uploadHttp.auth_token = token:string_of("access_token")
    else
        local tokenFiles = chilkat.FileAccess.new()
        if tokenFiles:file_exists("qa_data/tokens/oneDrive-sharepoint.json") then
            local sharepointToken = chilkat.JsonObject.new()
            sharepointToken.strict = true
            success = sharepointToken:load_file("qa_data/tokens/oneDrive-sharepoint.json")
            if not success then
                print("Could not read the private SharePoint token cache.")
                return
            end

            if (sharepointToken:json_type_of("host") ~= 1) or (sharepointToken:string_of_equals("host", "", true)) then
                print("Expected a nonempty host in the JSON.")
                return
            end

            if (sharepointToken:json_type_of("access_token") ~= 1) or (sharepointToken:string_of_equals("access_token", "", true)) then
                print("Expected a nonempty access_token in the JSON.")
                return
            end

            -- Configure host independently; never trust a response URL to choose a new credential audience.
            if (serviceHost:contents_equal(sharepointToken:string_of("host"), false)) and (serviceUrl.port == 443) then
                uploadHttp.auth_token = sharepointToken:string_of("access_token")
            end
        end
    end
end

-- Without a matching token, only a still-valid preauthenticated URL can succeed.
local expires = chilkat.DateTime.new()
local now = chilkat.DateTime.new()
success = expires:set_from_timestamp(receipt:string_of("expirationDateTime"))
if not success then
    print("Invalid session expiry.")
    return
end

success = now:set_from_current_system_time()
if not success then
    print("Could not check the expiry.")
    return
end

if expires:diff_seconds(now) <= 0 then
    print("Session expired. Reconcile the destination before creating a replacement.")
    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.
local uploadResp = chilkat.HttpResponse.new()
local session = chilkat.JsonObject.new()
session.strict = true
local offset = 0
if resuming then
    -- Server status is authoritative after a lost response; a local offset might be stale.
    success = uploadHttp:http_no_body("GET", uploadUrl, uploadResp)
    if (uploadResp.status_code == 401) or (uploadResp.status_code == 403) then
        print("Session authentication or permission failure. HTTP status: " .. uploadResp.status_code)
        print("Refresh the correct service token or check grants, then resume this receipt. Do not recreate blindly.")
        return
    end

    if (not success) and (uploadResp.status_code == 0) then
        print("No HTTP response received; inspect diagnostics privately and reconcile writes before retrying.")
        return
    end

    if uploadResp.status_code ~= 200 then
        print("Unexpected HTTP status: " .. uploadResp.status_code)
        print("Request ID: " .. uploadResp:get_header_field("request-id"))
        if uploadResp.status_code == 429 then
            print("Retry-After: " .. uploadResp:get_header_field("Retry-After"))
        end

        return
    end

    success = session:load(uploadResp.body_str)
    if not success then
        print("Expected a well-formed JSON response.")
        return
    end
else
    session:update_string("nextExpectedRanges[0]", "0-")
end

local range = chilkat.StringBuilder.new()
local contentRange = chilkat.StringBuilder.new()
local offsetText = chilkat.StringBuilder.new()
local countText = chilkat.StringBuilder.new()
local chunkRequest = chilkat.HttpRequest.new()
chunkRequest.http_verb = "PUT"
chunkRequest.content_type = "application/octet-stream"
while offset < fileSize do
    -- This sequential example handles a single open-ended remaining range.
    -- Stop rather than misinterpreting multiple holes or a bounded range.
    if (session:size_of_array("nextExpectedRanges") ~= 1) or (session:json_type_of("nextExpectedRanges[0]") ~= 1) then
        print("Expected one remaining range; inspect session status before continuing.")
        return
    end

    range:set_string(session:string_of("nextExpectedRanges[0]"))
    matched = range:regex_match("\\A[0-9]{1,9}-\\z", match, 100)
    if matched ~= 1 then
        print("Expected a single open-ended offset such as 3276800-; no more bytes sent.")
        return
    end

    local replacements = range:replace("-", "")
    local nextOffset = range.int_value
    if (nextOffset < offset) or (nextOffset >= fileSize) then
        print("Unexpected server offset; retain the receipt and reconcile.")
        return
    end

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

    local endByte = offset + chunkSize - 1
    offsetText:clear()
    offsetText:append_int(offset)
    countText:clear()
    countText:append_int(chunkSize)
    success = chunkRequest:stream_chunk_from_file(filePath, offsetText:get_as_string(), countText:get_as_string())
    if not success then
        print("Could not prepare the file chunk.")
        return
    end

    contentRange:set_string("bytes ")
    contentRange:append_int(offset)
    contentRange:append("-")
    contentRange:append_int(endByte)
    contentRange:append("/")
    contentRange:append_int(fileSize)
    chunkRequest:add_header("Content-Range", contentRange:get_as_string())
    success = uploadHttp:http_req(uploadUrl, chunkRequest, uploadResp)
    if (uploadResp.status_code == 401) or (uploadResp.status_code == 403) then
        print("Session authentication or permission failure. HTTP status: " .. uploadResp.status_code)
        print("Refresh the correct service token or check grants, then resume this receipt. Do not recreate blindly.")
        return
    end

    if (not success) and (uploadResp.status_code == 0) then
        print("Upload response lost. Retain this receipt and query the session on the next run.")
        return
    end

    if (uploadResp.status_code == 200) or (uploadResp.status_code == 201) then
        if (endByte + 1) ~= fileSize then
            print("Unexpected early completion; reconcile the target.")
            return
        end

        success = result:load(uploadResp.body_str)
        if not success then
            print("Upload may have completed but its response is invalid; reconcile before retrying.")
            return
        end

        if (result:json_type_of("id") ~= 1) or (result:string_of_equals("id", "", true)) then
            print("Expected a nonempty id in the JSON.")
            return
        end

        receipt:update_string("status", "complete")
        receipt:update_string("itemId", result:string_of("id"))
        success = receipt:write_file(receiptPath)
        if not success then
            print("Upload completed but saving its ID failed; reconcile before retrying.")
            return
        end

        print("Upload completed. Item ID: " .. result:string_of("id"))
        return
    end

    if (not success) and (uploadResp.status_code == 0) then
        print("No HTTP response received; inspect diagnostics privately and reconcile writes before retrying.")
        return
    end

    if uploadResp.status_code ~= 202 then
        print("Unexpected HTTP status: " .. uploadResp.status_code)
        print("Request ID: " .. uploadResp:get_header_field("request-id"))
        if uploadResp.status_code == 429 then
            print("Retry-After: " .. uploadResp:get_header_field("Retry-After"))
        end

        return
    end

    success = session:load(uploadResp.body_str)
    if not success then
        print("Expected a well-formed JSON response.")
        return
    end

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

    offset = endByte + 1
    if (session:json_type_of("expirationDateTime") ~= 1) or (session:string_of_equals("expirationDateTime", "", true)) then
        print("Expected a nonempty expirationDateTime in the JSON.")
        return
    end

    receipt:update_string("expirationDateTime", session:string_of("expirationDateTime"))
    receipt:update_int("confirmedOffset", offset)
    success = receipt:write_file(receiptPath)
    if not success then
        print("Could not checkpoint progress; retain the prior receipt and query the server on resume.")
        return
    end

    print("Uploaded bytes so far: " .. offset)
end