OneDrive: Copy a File or Folder and Monitor Completion
See more OneDrive Examples
Creates a new item: copy a selected item to an explicitly addressed destination folder. A folder copy includes its descendants. The first run submits the request and saves its monitor URL; subsequent runs make one status request without submitting another copy. Use a fresh private receipt for each intentional operation and account. Schedule checks with backoff and honor Retry-After; 202 means accepted, not finished.
The receipt starts as pending before submission. A lost response or failed write requires reconciling the destination before starting again. Completed and failed receipts prevent automatic resubmission. Monitoring accepts JSON completion and 303 completion responses without automatically following redirects. A resourceId, when returned, is the new item ID and stays a string. Monitor URLs can expire; they are private, temporary operation state.
The default conflict behavior fails on a name collision. Copies inherit destination permissions and do not retain all source metadata. This example copies current content only. Copying all versions requires includeAllVersionHistory=true; Microsoft documents a current issue when it is combined with name, so copy first without name and rename afterward for that workflow. Folder copies are limited to 30,000 items; app-only cross-geo copy is unsupported.
Microsoft has announced changes to preauthenticated URLs beginning April 1, 2027. The example supports Graph-hosted URLs with the Graph token and an explicitly configured SharePoint host with a separate SharePoint-audience token. A legacy preauthenticated URL is requested without a bearer token. Never forward the Graph token to a SharePoint or content host. If required, prepare private qa_data/tokens/oneDrive-sharepoint.json with host and access_token from a separately authorized SharePoint token acquisition; token refresh must preserve that audience. A 401 requires checking the correct token audience or URL expiry, not blindly adding credentials.
Permission: Files.ReadWrite.
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 Lua Downloads
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 itemId = "YOUR_ITEM_ID"
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(itemId))
local destinationDriveId = "YOUR_DESTINATION_DRIVE_ID"
local destinationFolderId = "YOUR_DESTINATION_FOLDER_ID"
local newName = "copied-file.txt"
-- Use a separate private receipt for each copy operation and account.
local accountKey = "YOUR_LOCAL_ACCOUNT_KEY"
local receiptPath = "qa_data/oneDrive/copy-receipt.json"
local fac = chilkat.FileAccess.new()
success = fac:dir_ensure_exists("qa_data/oneDrive")
if not success then
print("Could not create the private receipt directory.")
return
end
local receipt = chilkat.JsonObject.new()
receipt.strict = true
if fac:file_exists(receiptPath) then
success = receipt:load_file(receiptPath)
if not success then
print("Invalid receipt; reconcile the existing operation before starting another.")
return
end
if not receipt:string_of_equals("accountKey", accountKey, true) then
print("Receipt belongs to another copy operation; no request sent.")
return
end
if not receipt:string_of_equals("sourceDriveId", driveId, true) then
print("Receipt belongs to another copy operation; no request sent.")
return
end
if not receipt:string_of_equals("sourceItemId", itemId, true) then
print("Receipt belongs to another copy operation; no request sent.")
return
end
if not receipt:string_of_equals("destinationDriveId", destinationDriveId, true) then
print("Receipt belongs to another copy operation; no request sent.")
return
end
if not receipt:string_of_equals("destinationFolderId", destinationFolderId, true) then
print("Receipt belongs to another copy operation; no request sent.")
return
end
if not receipt:string_of_equals("name", newName, true) then
print("Receipt belongs to another copy operation; no request sent.")
return
end
if receipt:string_of_equals("status", "completed", true) then
print("This copy already completed. Item ID: " .. receipt:string_of("resourceId"))
return
end
if receipt:string_of_equals("status", "failed", true) then
print("The saved copy failed. Review its error and destination before starting another operation.")
return
end
if not receipt:string_of_equals("status", "monitoring", true) then
print("Copy outcome is uncertain; reconcile the destination before replacing this receipt.")
return
end
if (receipt:json_type_of("monitorUrl") ~= 1) or (receipt:string_of_equals("monitorUrl", "", true)) then
print("Expected a nonempty monitorUrl in the JSON.")
return
end
else
receipt:update_string("accountKey", accountKey)
receipt:update_string("sourceDriveId", driveId)
receipt:update_string("sourceItemId", itemId)
receipt:update_string("destinationDriveId", destinationDriveId)
receipt:update_string("destinationFolderId", destinationFolderId)
receipt:update_string("name", newName)
-- Save intent before POST so a lost response cannot cause an automatic duplicate copy.
receipt:update_string("status", "pending")
success = receipt:write_file(receiptPath)
if not success then
print("Could not save the copy intent; nothing submitted.")
return
end
local body = chilkat.JsonObject.new()
body:update_string("parentReference.driveId", destinationDriveId)
body:update_string("parentReference.id", destinationFolderId)
body:update_string("name", newName)
endpoint:append("/copy")
-- Omit conflictBehavior: the default is fail, and the query option is not supported by personal OneDrive.
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 ~= 202 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
local monitorUrl = resp:get_header_field("Location")
if monitorUrl == "" then
print("Accepted without a monitor URL; keep the pending receipt and reconcile the destination.")
return
end
receipt:update_string("monitorUrl", monitorUrl)
receipt:update_string("status", "monitoring")
success = receipt:write_file(receiptPath)
if not success then
print("Accepted, but receipt save failed. Do not repeat POST; reconcile the destination.")
return
end
print("Copy accepted. Run again later to check its status; honor Retry-After.")
print("Retry-After: " .. resp:get_header_field("Retry-After"))
return
end
-- One status request per run. The caller schedules the next run with backoff and Retry-After.
local statusUrl = receipt:string_of("monitorUrl")
local serviceUrl = chilkat.Url.new()
success = serviceUrl:parse_url(statusUrl)
if not success then
print("Invalid 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
local monitorHttp = chilkat.Http.new()
monitorHttp.require_ssl_cert_verify = true
monitorHttp.follow_redirects = false
monitorHttp.connect_timeout = 20
monitorHttp.read_timeout = 120
local serviceHost = chilkat.StringBuilder.new()
serviceHost:append(serviceUrl.host)
if (serviceHost:contents_equal("graph.microsoft.com", false)) and (serviceUrl.port == 443) then
monitorHttp.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
-- host is a configured exact hostname, not a URL and not obtained from the service response.
if (serviceHost:contents_equal(sharepointToken:string_of("host"), false)) and (serviceUrl.port == 443) then
monitorHttp.auth_token = sharepointToken:string_of("access_token")
end
end
end
-- With no matching token configured, only a still-valid preauthenticated URL can succeed.
success = monitorHttp:http_no_body("GET", statusUrl, 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) and ((resp.status_code ~= 202) and (resp.status_code ~= 303)) 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
local completed = resp.status_code == 303
if resp.body_str ~= "" then
success = result:load(resp.body_str)
if not success then
print("Invalid monitor JSON; keep the receipt and inspect the operation.")
return
end
if result:string_of_equals("status", "completed", false) then
completed = true
end
if result:string_of_equals("status", "failed", false) then
receipt:update_string("status", "failed")
receipt:update_string("errorCode", result:string_of("error.code"))
success = receipt:write_file(receiptPath)
if not success then
print("Could not save the failed-operation receipt.")
return
end
print("Copy failed: " .. result:string_of("error.code"))
return
end
end
if completed then
receipt:update_string("status", "completed")
if result:json_type_of("resourceId") == 1 then
receipt:update_string("resourceId", result:string_of("resourceId"))
end
success = receipt:write_file(receiptPath)
if not success then
print("Copy completed but the receipt could not be saved. Reconcile before another copy.")
return
end
print("Copy completed. Destination drive ID: " .. destinationDriveId)
print("New item ID, if returned: " .. receipt:string_of("resourceId"))
-- A 303 without a JSON resourceId still indicates completion. Look up the destination by name if needed.
-- Do not follow Location/resourceLocation with the Graph bearer token automatically.
else
print("Copy not completed. Status: " .. result:string_of("status"))
print("Percent complete, if returned: " .. result:string_of("percentageComplete"))
print("Retry-After: " .. resp:get_header_field("Retry-After"))
end