Sample code for 30+ languages & platforms
Lua Requires Chilkat v11.0.0+

OneDrive -- Upload Large Files with an Upload Session

See more OneDrive Examples

Demonstrates how to upload large files with an upload session. See OneDrive Upload Session for more general information.

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

-- This example requires the Chilkat API to have been previously unlocked.
-- See Global Unlock Sample for sample code.

-- This example uses the OAuth client credentials flow.
-- See How to Create an Azure App Registration for OAuth 2.0 Client Credentials

-- Use your client ID, client secret, and tenant ID in the following lines
local json = chilkat.JsonObject.new()
json:update_string("client_id", "2871da2c-8176-4b7f-869b-2311aa82e743")
json:update_string("client_secret", "2hu9Q~r5QuryUcEkNbg1btLtnfU1VUXzhSCG6brH")
json:update_string("scope", "https://graph.microsoft.com/.default")
json:update_string("token_endpoint", "https://login.microsoftonline.com/114d7ed6-71bf-4dbe-a866-748364121bf2/oauth2/v2.0/token")

local http = chilkat.Http.new()
http.auth_token = json:emit()

-- ----------------------------------------------------------------------------
-- Step 1: Create an upload session

-- To begin a large file upload, your app must first request a new upload session. This creates a
-- temporary storage location where the bytes of the file will be saved until the complete file is uploaded.
-- Once the last byte of the file has been uploaded the upload session is completed and the final file is shown
-- in the destination folder.

-- Send the following POST to create an upload session:
-- If not using "me", then the path should be /v1.0/users/{id | userPrincipalName}/...
-- POST /v1.0/users/{user_id}/drive/root:/{path_to_item}:/createUploadSession

http:set_url_var("path_to_item", "/somefolder/big.zip")
http:set_url_var("user_id", "4fe732c3-322e-4a6b-b729-2fd1eb5c6104")
local url = "https://graph.microsoft.com/v1.0/users/{$user_id}/drive/root:/{$path_to_item}:/createUploadSession"
local resp = chilkat.HttpResponse.new()
local success = http:http_str("POST", url, "{}", "utf-8", "application/json", resp)
if not success then
    print(http.last_error_text)
    return
end

-- If successful, a 200 status code is returned, with the session details (in JSON format).
local jsonSession = chilkat.JsonObject.new()
jsonSession.emit_compact = false
jsonSession:load(resp.body_str)

if resp.status_code ~= 200 then
    print(jsonSession:emit())
    print("Response status = " .. resp.status_code)
    return
end

print(jsonSession:emit())

-- A sample response:

--     {
--       "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#microsoft.graph.uploadSession",
--       "uploadUrl": "https://api.onedrive.com/rup/3a33fceb9b74cc15/eyJSZXNvdXJjZUlEI ... 65yDYUiS3JTDnnhqCHxw",
--       "expirationDateTime": "2017-06-11T12:40:23.239Z",
--       "nextExpectedRanges": [
--         "0-"
--       ]
--     }
--

-- ----------------------------------------------------------------------------
-- Step 2: Upload Data in Segments (a.k.a. Fragments or Chunks)

-- Microsoft states this requirement: Use a fragment size that is a multiple of 320 KiB (320 * 1024 bytes).
-- Failing to use a fragment size that is a multiple of 320 KiB can result in large file transfers failing after the
-- last fragment is uploaded.  (Note: This is a detail imposed by Microsoft's OneDrive server-side implementation.)

local fragSize = 320 * 1024
local localFilePath = "qa_data/zips/big.zip"

-- Upload the file big.zip in 320KiB segments.
-- Note: The FileSize method returns a signed 32-bit integer.  If the file is potentially larger than 2GB, call FileSizeStr instead to return
-- the size of the file as a string, then convert to an integer value.
local fac = chilkat.FileAccess.new()
local fileSize = fac:file_size(localFilePath)

-- Open the file to get the number of fragments.
success = fac:open_for_read(localFilePath)
if not success then
    print(fac.last_error_text)
    return
end

local numFragments = fac:get_num_blocks(fragSize)
fac:file_close()

local i = 0

print("fileSize = " .. fileSize)
print("numFragments = " .. numFragments)

local uploadUrl = chilkat.Url.new()
uploadUrl:parse_url(jsonSession:string_of("uploadUrl"))

json.emit_compact = false

local req = chilkat.HttpRequest.new()
req.http_verb = "PUT"
req.path = uploadUrl.path_with_query_params
req.content_type = "application/octet-stream"

local sbOffset = chilkat.StringBuilder.new()
local sbNumBytes = chilkat.StringBuilder.new()
local sbRange = chilkat.StringBuilder.new()

-- IMPORTANT: The uploadUrl is a temporary URL to be used to upload the fragment.
-- It requires no authentication (because the URL itself could only have been obtained from an authenticated
-- request to start the upload session).  Therefore, do not allow the upload URL to be publicly seen,
-- otherwise anybody could upload to your OneDrive.
http.auth_token = ""

local bytesRemaining = fileSize
while i < numFragments do
    -- The success response code for intermediate chunks is 202,
    -- whereas the final chunk will have a 201 success response where
    -- the response body is the JSON DriveItem.
    local chunkSize = fragSize
    local expectedStatusCode = 202
    if bytesRemaining < chunkSize then
        chunkSize = bytesRemaining
        expectedStatusCode = 201
    end

    print("  this chunkSize = " .. chunkSize)

    -- Indicate the fragment in the local file to be streamed in the upload.
    sbOffset:clear()
    sbOffset:append_int(i * fragSize)
    sbNumBytes:clear()
    sbNumBytes:append_int(chunkSize)
    req:stream_chunk_from_file(localFilePath, sbOffset:get_as_string(), sbNumBytes:get_as_string())

    -- The Content-Range header field must be set for this fragment.  For example:
    -- Content-Range: bytes 0-25/128
    sbRange:set_string("bytes start-end/fileSize")
    local numReplaced = sbRange:replace_i("start", i * fragSize)
    numReplaced = sbRange:replace_i("end", i * fragSize + chunkSize - 1)
    numReplaced = sbRange:replace_i("fileSize", fileSize)
    req:add_header("Content-Range", sbRange:get_as_string())
    print("  this content-range: " .. sbRange:get_as_string())

    local domain = uploadUrl.host
    success = http:http_sreq(domain, 443, true, req, resp)
    if not success then
        print(http.last_error_text)
        return
    end

    json:load(resp.body_str)
    -- A 202 response status code indicates success.
    if resp.status_code ~= expectedStatusCode then
        print(json:emit())
        print("Response status = " .. resp.status_code)
        return
    end

    print(json:emit())
    print("---- Chunk " .. i .. " uploaded ----")

    bytesRemaining = bytesRemaining - chunkSize
    i = i + 1
end

print("data uploaded.")

-- ----------------------------------------------------------------------------
-- Sample output for the above session:

-- {
--   "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#microsoft.graph.uploadSession",
--   "uploadUrl": "https://api.onedrive.com/rup/3a33fceb9b74cc15/eyJSZXNvd ... QoKK2iuh1A",
--   "expirationDateTime": "2017-06-11T14:04:45.438Z",
--   "nextExpectedRanges": [
--     "0-"
--   ]
-- }
--
-- fileSize = 1366807
-- numFragments = 5
--   this chunkSize = 327680
--   this content-range: bytes 0-327679/1366807
-- {
--   "expirationDateTime": "2017-06-11T14:04:45.438Z",
--   "nextExpectedRanges": [
--     "327680-1366806"
--   ]
-- }
--
-- ---- Chunk 0 uploaded ----
--   this chunkSize = 327680
--   this content-range: bytes 327680-655359/1366807
-- {
--   "expirationDateTime": "2017-06-11T14:04:45.438Z",
--   "nextExpectedRanges": [
--     "655360-1366806"
--   ]
-- }
--
-- ---- Chunk 1 uploaded ----
--   this chunkSize = 327680
--   this content-range: bytes 655360-983039/1366807
-- {
--   "expirationDateTime": "2017-06-11T14:04:45.438Z",
--   "nextExpectedRanges": [
--     "983040-1366806"
--   ]
-- }
--
-- ---- Chunk 2 uploaded ----
--   this chunkSize = 327680
--   this content-range: bytes 983040-1310719/1366807
-- {
--   "expirationDateTime": "2017-06-11T14:04:45.438Z",
--   "nextExpectedRanges": [
--     "1310720-1366806"
--   ]
-- }
--
-- ---- Chunk 3 uploaded ----
--   this chunkSize = 56087
--   this content-range: bytes 1310720-1366806/1366807
-- {
--   "createdBy": {
--     "application": {
--       "displayName": "Chilkat",
--       "id": "441c9990"
--     },
--     "user": {
--       "id": "3a33fceb9b74cc15"
--     }
--   },
--   "createdDateTime": "2017-06-04T14:04:47.247Z",
--   "cTag": "aYzozQTMzRkNFQjlCNzRDQzE1ITQ4NjguMjU3",
--   "eTag": "aM0EzM0ZDRUI5Qjc0Q0MxNSE0ODY4LjA",
--   "id": "3A33FCEB9B74CC15!4868",
--   "lastModifiedBy": {
--     "application": {
--       "displayName": "Chilkat",
--       "id": "441c9990"
--     },
--     "user": {
--       "id": "3a33fceb9b74cc15"
--     }
--   },
--   "lastModifiedDateTime": "2017-06-04T14:04:47.247Z",
--   "name": "big.zip",
--   "parentReference": {
--     "driveId": "3a33fceb9b74cc15",
--     "id": "3A33FCEB9B74CC15!4862",
--     "name": "someFolder",
--     "path": "/drive/root:/someFolder"
--   },
--   "size": 1366807,
--   "webUrl": "https://1drv.ms/u/s!ABXMdJvr_DM6pgQ",
--   "file": {
--     "hashes": {
--       "sha1Hash": "252059AA13004220DB912B97D4D3FF9599CCD8D9"
--     },
--     "mimeType": "application/zip"
--   },
--   "fileSystemInfo": {
--     "createdDateTime": "2017-06-04T14:04:47.246Z",
--     "lastModifiedDateTime": "2017-06-04T14:04:47.246Z"
--   },
--   "tags": [
--   ],
--   "lenses": [
--   ]
-- }
--
-- Response status = 201