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 Swift Downloads
func chilkatTest() {
var success: Bool = 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.
let token = CkoJsonObject()!
token.strict = true
success = token.loadFile(path: "qa_data/tokens/oneDrive.json")
if success != true {
print("Could not load the private OneDrive token cache.")
return
}
if (token.jsonType(of: "access_token").intValue != 1) || (token.string(ofEquals: "access_token", value: "", caseSensitive: true) == true) {
print("Expected a nonempty access_token in the JSON.")
return
}
let http = CkoHttp()!
http.authToken = token.string(of: "access_token")
http.requireSslCertVerify = true
http.followRedirects = false
http.connectTimeout = 20
http.readTimeout = 120
http.setRequestHeader(name: "Accept", value: "application/json")
let resp = CkoHttpResponse()!
let result = CkoJsonObject()!
result.strict = true
var driveId: String? = "YOUR_DRIVE_ID"
var parentId: String? = "YOUR_PARENT_FOLDER_ID"
var fileName: String? = "large.bin"
var filePath: String? = "qa_data/large/sample.bin"
var receiptPath: String? = "qa_data/oneDrive/upload-session.json"
let fac = CkoFileAccess()!
var sizeString: String? = fac.fileSizeStr(filePath: filePath)
if fac.lastMethodSuccess != true {
print("Could not determine the source file size.")
return
}
let sizeText = CkoStringBuilder()!
sizeText.append(value: sizeString)
let match = CkoJsonObject()!
var matched: Int = sizeText.regexMatch(pattern: "\\A[0-9]{1,9}\\z", json: match, timeoutMs: 100).intValue
if matched != 1 {
print("File size exceeds this example's supported range.")
return
}
var fileSize: Int = sizeText.intValue.intValue
if (fileSize < 1) || (fileSize > 999999999) {
print("This example supports nonempty files up to 999,999,999 bytes; its int arithmetic is deliberately bounded.")
return
}
success = fac.dirEnsureExists(dirPath: "qa_data/oneDrive")
if success != true {
print("Could not create the private receipt directory.")
return
}
let hash = CkoCrypt2()!
hash.hashAlgorithm = "sha256"
hash.encodingMode = "hex"
var fileHash: String? = hash.hashFileENC(path: filePath)
if hash.lastMethodSuccess != true {
print("Could not fingerprint the source file.")
return
}
let receipt = CkoJsonObject()!
receipt.strict = true
var resuming: Bool = fac.fileExists(path: receiptPath)
if resuming == true {
success = receipt.loadFile(path: receiptPath)
if success != true {
print("Invalid receipt; reconcile the target before another upload.")
return
}
if (receipt.string(ofEquals: "driveId", value: driveId, caseSensitive: true) != true) || (receipt.string(ofEquals: "parentId", value: parentId, caseSensitive: true) != true) || (receipt.string(ofEquals: "name", value: fileName, caseSensitive: true) != true) || (receipt.string(ofEquals: "fileHash", value: fileHash, caseSensitive: true) != true) || (receipt.int(of: "fileSize").intValue != fileSize) {
print("Receipt does not match the drive, parent, name, and file; no request sent.")
return
}
if receipt.string(ofEquals: "status", value: "complete", caseSensitive: true) == true {
print("Already uploaded. Item ID: \(receipt.string(of: "itemId")!)")
return
}
if receipt.string(ofEquals: "status", value: "uploading", caseSensitive: true) != true {
print("Previous session creation is uncertain; inspect the pending receipt before retrying.")
return
}
if (receipt.jsonType(of: "uploadUrl").intValue != 1) || (receipt.string(ofEquals: "uploadUrl", value: "", caseSensitive: true) == true) {
print("Expected a nonempty uploadUrl in the JSON.")
return
}
if (receipt.jsonType(of: "expirationDateTime").intValue != 1) || (receipt.string(ofEquals: "expirationDateTime", value: "", caseSensitive: true) == true) {
print("Expected a nonempty expirationDateTime in the JSON.")
return
}
}
else {
let endpoint = CkoStringBuilder()!
endpoint.append(value: "https://graph.microsoft.com/v1.0/drives/")
endpoint.append(value: http.urlEncode(str: driveId))
endpoint.append(value: "/items/")
endpoint.append(value: http.urlEncode(str: parentId))
endpoint.append(value: ":/")
endpoint.append(value: http.urlEncode(str: fileName))
endpoint.append(value: ":/createUploadSession")
let body = CkoJsonObject()!
body.updateString(jsonPath: "item.name", value: fileName)
body.updateString(jsonPath: "item.\"@microsoft.graph.conflictBehavior\"", value: "fail")
receipt.updateString(jsonPath: "driveId", value: driveId)
receipt.updateString(jsonPath: "parentId", value: parentId)
receipt.updateString(jsonPath: "name", value: fileName)
receipt.updateString(jsonPath: "fileHash", value: fileHash)
receipt.updateInt(jsonPath: "fileSize", value: fileSize)
receipt.updateString(jsonPath: "status", value: "pending")
success = receipt.writeFile(path: receiptPath)
if success != true {
print("Could not save the pending receipt; no session created.")
return
}
success = http.httpJson(verb: "POST", url: endpoint.getAsString(), json: body, contentType: "application/json", response: resp)
if (success != true) && (resp.statusCode.intValue == 0) {
print("No HTTP response received; inspect diagnostics privately and reconcile writes before retrying.")
return
}
if (resp.statusCode.intValue != 200) {
print("Unexpected HTTP status: \(resp.statusCode.intValue)")
print("Request ID: \(resp.getHeaderField(fieldName: "request-id")!)")
if resp.statusCode.intValue == 429 {
print("Retry-After: \(resp.getHeaderField(fieldName: "Retry-After")!)")
}
return
}
success = result.load(json: resp.bodyStr)
if success != true {
print("Expected a well-formed JSON response.")
return
}
if (result.jsonType(of: "uploadUrl").intValue != 1) || (result.string(ofEquals: "uploadUrl", value: "", caseSensitive: true) == true) {
print("Expected a nonempty uploadUrl in the JSON.")
return
}
if (result.jsonType(of: "expirationDateTime").intValue != 1) || (result.string(ofEquals: "expirationDateTime", value: "", caseSensitive: true) == true) {
print("Expected a nonempty expirationDateTime in the JSON.")
return
}
receipt.updateString(jsonPath: "uploadUrl", value: result.string(of: "uploadUrl"))
receipt.updateString(jsonPath: "expirationDateTime", value: result.string(of: "expirationDateTime"))
receipt.updateString(jsonPath: "status", value: "uploading")
success = receipt.writeFile(path: receiptPath)
if success != true {
print("Session created but receipt save failed; reconcile before another creation.")
return
}
}
var uploadUrl: String? = receipt.string(of: "uploadUrl")
let serviceUrl = CkoUrl()!
success = serviceUrl.parse(url: uploadUrl)
if success != true {
print("Invalid returned service URL.")
return
}
if (serviceUrl.ssl != true) || (serviceUrl.host == "") || (serviceUrl.login != "") || (serviceUrl.password != "") {
print("Expected an HTTPS service URL without embedded login credentials.")
return
}
// Returned URLs can be preauthenticated, Graph-authenticated, or SharePoint-authenticated.
// Never copy Graph authorization to an arbitrary host, and never follow redirects automatically.
let uploadHttp = CkoHttp()!
uploadHttp.requireSslCertVerify = true
uploadHttp.followRedirects = false
uploadHttp.connectTimeout = 20
uploadHttp.readTimeout = 120
let serviceHost = CkoStringBuilder()!
serviceHost.append(value: serviceUrl.host)
let serviceQuery = CkoStringBuilder()!
serviceQuery.append(value: serviceUrl.query)
let authMatch = CkoJsonObject()!
var authMatched: Int = serviceQuery.regexMatch(pattern: "(?i)(?:^|[?&])tempauth=[^&]+", json: authMatch, timeoutMs: 100).intValue
if authMatched < 0 {
print("Could not inspect the service URL query.")
return
}
// tempauth carries its own authorization. Do not add a bearer token to that legacy URL.
if authMatched == 0 {
if (serviceHost.contentsEqual(str: "graph.microsoft.com", caseSensitive: false) == true) && (serviceUrl.port.intValue == 443) {
uploadHttp.authToken = token.string(of: "access_token")
}
else {
let tokenFiles = CkoFileAccess()!
if tokenFiles.fileExists(path: "qa_data/tokens/oneDrive-sharepoint.json") == true {
let sharepointToken = CkoJsonObject()!
sharepointToken.strict = true
success = sharepointToken.loadFile(path: "qa_data/tokens/oneDrive-sharepoint.json")
if success != true {
print("Could not read the private SharePoint token cache.")
return
}
if (sharepointToken.jsonType(of: "host").intValue != 1) || (sharepointToken.string(ofEquals: "host", value: "", caseSensitive: true) == true) {
print("Expected a nonempty host in the JSON.")
return
}
if (sharepointToken.jsonType(of: "access_token").intValue != 1) || (sharepointToken.string(ofEquals: "access_token", value: "", caseSensitive: true) == true) {
print("Expected a nonempty access_token in the JSON.")
return
}
// Configure host independently; never trust a response URL to choose a new credential audience.
if (serviceHost.contentsEqual(str: sharepointToken.string(of: "host"), caseSensitive: false) == true) && (serviceUrl.port.intValue == 443) {
uploadHttp.authToken = sharepointToken.string(of: "access_token")
}
}
}
}
// Without a matching token, only a still-valid preauthenticated URL can succeed.
let expires = CkoDateTime()!
let now = CkoDateTime()!
success = expires.set(fromTimestamp: receipt.string(of: "expirationDateTime"))
if success != true {
print("Invalid session expiry.")
return
}
success = now.setFromCurrentSystemTime()
if success != true {
print("Could not check the expiry.")
return
}
if expires.diffSeconds(dateTimeArg: now).intValue <= 0 {
print("Session expired. Reconcile the destination before creating a replacement.")
return
}
// 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.
let uploadResp = CkoHttpResponse()!
let session = CkoJsonObject()!
session.strict = true
var offset: Int = 0
if resuming == true {
// Server status is authoritative after a lost response; a local offset might be stale.
success = uploadHttp.httpNoBody(verb: "GET", url: uploadUrl, response: uploadResp)
if (uploadResp.statusCode.intValue == 401) || (uploadResp.statusCode.intValue == 403) {
print("Session authentication or permission failure. HTTP status: \(uploadResp.statusCode.intValue)")
print("Refresh the correct service token or check grants, then resume this receipt. Do not recreate blindly.")
return
}
if (success != true) && (uploadResp.statusCode.intValue == 0) {
print("No HTTP response received; inspect diagnostics privately and reconcile writes before retrying.")
return
}
if (uploadResp.statusCode.intValue != 200) {
print("Unexpected HTTP status: \(uploadResp.statusCode.intValue)")
print("Request ID: \(uploadResp.getHeaderField(fieldName: "request-id")!)")
if uploadResp.statusCode.intValue == 429 {
print("Retry-After: \(uploadResp.getHeaderField(fieldName: "Retry-After")!)")
}
return
}
success = session.load(json: uploadResp.bodyStr)
if success != true {
print("Expected a well-formed JSON response.")
return
}
}
else {
session.updateString(jsonPath: "nextExpectedRanges[0]", value: "0-")
}
let range = CkoStringBuilder()!
let contentRange = CkoStringBuilder()!
let offsetText = CkoStringBuilder()!
let countText = CkoStringBuilder()!
let chunkRequest = CkoHttpRequest()!
chunkRequest.httpVerb = "PUT"
chunkRequest.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.size(ofArray: "nextExpectedRanges").intValue != 1) || (session.jsonType(of: "nextExpectedRanges[0]").intValue != 1) {
print("Expected one remaining range; inspect session status before continuing.")
return
}
range.setString(value: session.string(of: "nextExpectedRanges[0]"))
matched = range.regexMatch(pattern: "\\A[0-9]{1,9}-\\z", json: match, timeoutMs: 100).intValue
if matched != 1 {
print("Expected a single open-ended offset such as 3276800-; no more bytes sent.")
return
}
var replacements: Int = range.replace(value: "-", replacement: "").intValue
var nextOffset: Int = range.intValue.intValue
if (nextOffset < offset) || (nextOffset >= fileSize) {
print("Unexpected server offset; retain the receipt and reconcile.")
return
}
offset = nextOffset
// 10 MiB is 32 * 320 KiB and is below the 60 MiB per-request limit.
var chunkSize: Int = 10485760
if (fileSize - offset) < chunkSize {
chunkSize = fileSize - offset
}
var endByte: Int = offset + chunkSize - 1
offsetText.clear()
offsetText.appendInt(value: offset)
countText.clear()
countText.appendInt(value: chunkSize)
success = chunkRequest.streamChunk(fromFile: filePath, offset: offsetText.getAsString(), numBytes: countText.getAsString())
if success != true {
print("Could not prepare the file chunk.")
return
}
contentRange.setString(value: "bytes ")
contentRange.appendInt(value: offset)
contentRange.append(value: "-")
contentRange.appendInt(value: endByte)
contentRange.append(value: "/")
contentRange.appendInt(value: fileSize)
chunkRequest.addHeader(name: "Content-Range", value: contentRange.getAsString())
success = uploadHttp.httpReq(url: uploadUrl, request: chunkRequest, response: uploadResp)
if (uploadResp.statusCode.intValue == 401) || (uploadResp.statusCode.intValue == 403) {
print("Session authentication or permission failure. HTTP status: \(uploadResp.statusCode.intValue)")
print("Refresh the correct service token or check grants, then resume this receipt. Do not recreate blindly.")
return
}
if (success != true) && (uploadResp.statusCode.intValue == 0) {
print("Upload response lost. Retain this receipt and query the session on the next run.")
return
}
if (uploadResp.statusCode.intValue == 200) || (uploadResp.statusCode.intValue == 201) {
if (endByte + 1) != fileSize {
print("Unexpected early completion; reconcile the target.")
return
}
success = result.load(json: uploadResp.bodyStr)
if success != true {
print("Upload may have completed but its response is invalid; reconcile before retrying.")
return
}
if (result.jsonType(of: "id").intValue != 1) || (result.string(ofEquals: "id", value: "", caseSensitive: true) == true) {
print("Expected a nonempty id in the JSON.")
return
}
receipt.updateString(jsonPath: "status", value: "complete")
receipt.updateString(jsonPath: "itemId", value: result.string(of: "id"))
success = receipt.writeFile(path: receiptPath)
if success != true {
print("Upload completed but saving its ID failed; reconcile before retrying.")
return
}
print("Upload completed. Item ID: \(result.string(of: "id")!)")
return
}
if (success != true) && (uploadResp.statusCode.intValue == 0) {
print("No HTTP response received; inspect diagnostics privately and reconcile writes before retrying.")
return
}
if (uploadResp.statusCode.intValue != 202) {
print("Unexpected HTTP status: \(uploadResp.statusCode.intValue)")
print("Request ID: \(uploadResp.getHeaderField(fieldName: "request-id")!)")
if uploadResp.statusCode.intValue == 429 {
print("Retry-After: \(uploadResp.getHeaderField(fieldName: "Retry-After")!)")
}
return
}
success = session.load(json: uploadResp.bodyStr)
if success != true {
print("Expected a well-formed JSON response.")
return
}
if (endByte + 1) == fileSize {
print("Final bytes returned 202, not a completed item. Retain the session and inspect its status.")
return
}
offset = endByte + 1
if (session.jsonType(of: "expirationDateTime").intValue != 1) || (session.string(ofEquals: "expirationDateTime", value: "", caseSensitive: true) == true) {
print("Expected a nonempty expirationDateTime in the JSON.")
return
}
receipt.updateString(jsonPath: "expirationDateTime", value: session.string(of: "expirationDateTime"))
receipt.updateInt(jsonPath: "confirmedOffset", value: offset)
success = receipt.writeFile(path: receiptPath)
if success != true {
print("Could not checkpoint progress; retain the prior receipt and query the server on resume.")
return
}
print("Uploaded bytes so far: \(offset)")
}
}