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 Objective-C Downloads
#import <CkoJsonObject.h>
#import <CkoHttp.h>
#import <CkoHttpResponse.h>
#import <NSString.h>
#import <CkoFileAccess.h>
#import <CkoStringBuilder.h>
#import <CkoCrypt2.h>
#import <CkoUrl.h>
#import <CkoDateTime.h>
#import <CkoHttpRequest.h>
BOOL success = NO;
// Assumes Chilkat is unlocked. See Global Unlock Sample.
success = NO;
// Obtain a delegated Graph token with this example's file permissions.
// See OneDrive OAuth2 with PKCE.
CkoJsonObject *token = [[CkoJsonObject alloc] init];
token.Strict = YES;
success = [token LoadFile: @"qa_data/tokens/oneDrive.json"];
if (success != YES) {
NSLog(@"%@",@"Could not load the private OneDrive token cache.");
return;
}
if (([[token JsonTypeOf: @"access_token"] intValue] != 1) || ([token StringOfEquals: @"access_token" value: @"" caseSensitive: YES] == YES)) {
NSLog(@"%@",@"Expected a nonempty access_token in the JSON.");
return;
}
CkoHttp *http = [[CkoHttp alloc] init];
http.AuthToken = [token StringOf: @"access_token"];
http.RequireSslCertVerify = YES;
http.FollowRedirects = NO;
http.ConnectTimeout = [NSNumber numberWithInt:20];
http.ReadTimeout = [NSNumber numberWithInt:120];
[http SetRequestHeader: @"Accept" value: @"application/json"];
CkoHttpResponse *resp = [[CkoHttpResponse alloc] init];
CkoJsonObject *result = [[CkoJsonObject alloc] init];
result.Strict = YES;
NSString *driveId = @"YOUR_DRIVE_ID";
NSString *parentId = @"YOUR_PARENT_FOLDER_ID";
NSString *fileName = @"large.bin";
NSString *filePath = @"qa_data/large/sample.bin";
NSString *receiptPath = @"qa_data/oneDrive/upload-session.json";
CkoFileAccess *fac = [[CkoFileAccess alloc] init];
NSString *sizeString = [fac FileSizeStr: filePath];
if (fac.LastMethodSuccess != YES) {
NSLog(@"%@",@"Could not determine the source file size.");
return;
}
CkoStringBuilder *sizeText = [[CkoStringBuilder alloc] init];
[sizeText Append: sizeString];
CkoJsonObject *match = [[CkoJsonObject alloc] init];
int matched = [[sizeText RegexMatch: @"\\A[0-9]{1,9}\\z" json: match timeoutMs: [NSNumber numberWithInt: 100]] intValue];
if (matched != 1) {
NSLog(@"%@",@"File size exceeds this example's supported range.");
return;
}
int fileSize = [sizeText.IntValue intValue];
if ((fileSize < 1) || (fileSize > 999999999)) {
NSLog(@"%@",@"This example supports nonempty files up to 999,999,999 bytes; its int arithmetic is deliberately bounded.");
return;
}
success = [fac DirEnsureExists: @"qa_data/oneDrive"];
if (success != YES) {
NSLog(@"%@",@"Could not create the private receipt directory.");
return;
}
CkoCrypt2 *hash = [[CkoCrypt2 alloc] init];
hash.HashAlgorithm = @"sha256";
hash.EncodingMode = @"hex";
NSString *fileHash = [hash HashFileENC: filePath];
if (hash.LastMethodSuccess != YES) {
NSLog(@"%@",@"Could not fingerprint the source file.");
return;
}
CkoJsonObject *receipt = [[CkoJsonObject alloc] init];
receipt.Strict = YES;
BOOL resuming = [fac FileExists: receiptPath];
if (resuming == YES) {
success = [receipt LoadFile: receiptPath];
if (success != YES) {
NSLog(@"%@",@"Invalid receipt; reconcile the target before another upload.");
return;
}
if (([receipt StringOfEquals: @"driveId" value: driveId caseSensitive: YES] != YES) || ([receipt StringOfEquals: @"parentId" value: parentId caseSensitive: YES] != YES) || ([receipt StringOfEquals: @"name" value: fileName caseSensitive: YES] != YES) || ([receipt StringOfEquals: @"fileHash" value: fileHash caseSensitive: YES] != YES) || ([[receipt IntOf: @"fileSize"] intValue] != fileSize)) {
NSLog(@"%@",@"Receipt does not match the drive, parent, name, and file; no request sent.");
return;
}
if ([receipt StringOfEquals: @"status" value: @"complete" caseSensitive: YES] == YES) {
NSLog(@"%@%@",@"Already uploaded. Item ID: ",[receipt StringOf: @"itemId"]);
return;
}
if ([receipt StringOfEquals: @"status" value: @"uploading" caseSensitive: YES] != YES) {
NSLog(@"%@",@"Previous session creation is uncertain; inspect the pending receipt before retrying.");
return;
}
if (([[receipt JsonTypeOf: @"uploadUrl"] intValue] != 1) || ([receipt StringOfEquals: @"uploadUrl" value: @"" caseSensitive: YES] == YES)) {
NSLog(@"%@",@"Expected a nonempty uploadUrl in the JSON.");
return;
}
if (([[receipt JsonTypeOf: @"expirationDateTime"] intValue] != 1) || ([receipt StringOfEquals: @"expirationDateTime" value: @"" caseSensitive: YES] == YES)) {
NSLog(@"%@",@"Expected a nonempty expirationDateTime in the JSON.");
return;
}
}
else {
CkoStringBuilder *endpoint = [[CkoStringBuilder alloc] init];
[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"];
CkoJsonObject *body = [[CkoJsonObject alloc] init];
[body UpdateString: @"item.name" value: fileName];
[body UpdateString: @"item.\"@microsoft.graph.conflictBehavior\"" value: @"fail"];
[receipt UpdateString: @"driveId" value: driveId];
[receipt UpdateString: @"parentId" value: parentId];
[receipt UpdateString: @"name" value: fileName];
[receipt UpdateString: @"fileHash" value: fileHash];
[receipt UpdateInt: @"fileSize" value: [NSNumber numberWithInt: fileSize]];
[receipt UpdateString: @"status" value: @"pending"];
success = [receipt WriteFile: receiptPath];
if (success != YES) {
NSLog(@"%@",@"Could not save the pending receipt; no session created.");
return;
}
success = [http HttpJson: @"POST" url: [endpoint GetAsString] json: body contentType: @"application/json" response: resp];
if ((success != YES) && ([resp.StatusCode intValue] == 0)) {
NSLog(@"%@",@"No HTTP response received; inspect diagnostics privately and reconcile writes before retrying.");
return;
}
if (([resp.StatusCode intValue] != 200)) {
NSLog(@"%@%d",@"Unexpected HTTP status: ",[resp.StatusCode intValue]);
NSLog(@"%@%@",@"Request ID: ",[resp GetHeaderField: @"request-id"]);
if ([resp.StatusCode intValue] == 429) {
NSLog(@"%@%@",@"Retry-After: ",[resp GetHeaderField: @"Retry-After"]);
}
return;
}
success = [result Load: resp.BodyStr];
if (success != YES) {
NSLog(@"%@",@"Expected a well-formed JSON response.");
return;
}
if (([[result JsonTypeOf: @"uploadUrl"] intValue] != 1) || ([result StringOfEquals: @"uploadUrl" value: @"" caseSensitive: YES] == YES)) {
NSLog(@"%@",@"Expected a nonempty uploadUrl in the JSON.");
return;
}
if (([[result JsonTypeOf: @"expirationDateTime"] intValue] != 1) || ([result StringOfEquals: @"expirationDateTime" value: @"" caseSensitive: YES] == YES)) {
NSLog(@"%@",@"Expected a nonempty expirationDateTime in the JSON.");
return;
}
[receipt UpdateString: @"uploadUrl" value: [result StringOf: @"uploadUrl"]];
[receipt UpdateString: @"expirationDateTime" value: [result StringOf: @"expirationDateTime"]];
[receipt UpdateString: @"status" value: @"uploading"];
success = [receipt WriteFile: receiptPath];
if (success != YES) {
NSLog(@"%@",@"Session created but receipt save failed; reconcile before another creation.");
return;
}
}
NSString *uploadUrl = [receipt StringOf: @"uploadUrl"];
CkoUrl *serviceUrl = [[CkoUrl alloc] init];
success = [serviceUrl ParseUrl: uploadUrl];
if (success != YES) {
NSLog(@"%@",@"Invalid returned service URL.");
return;
}
if ((serviceUrl.Ssl != YES) || (serviceUrl.Host == @"") || (serviceUrl.Login != @"") || (serviceUrl.Password != @"")) {
NSLog(@"%@",@"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.
CkoHttp *uploadHttp = [[CkoHttp alloc] init];
uploadHttp.RequireSslCertVerify = YES;
uploadHttp.FollowRedirects = NO;
uploadHttp.ConnectTimeout = [NSNumber numberWithInt:20];
uploadHttp.ReadTimeout = [NSNumber numberWithInt:120];
CkoStringBuilder *serviceHost = [[CkoStringBuilder alloc] init];
[serviceHost Append: serviceUrl.Host];
CkoStringBuilder *serviceQuery = [[CkoStringBuilder alloc] init];
[serviceQuery Append: serviceUrl.Query];
CkoJsonObject *authMatch = [[CkoJsonObject alloc] init];
int authMatched = [[serviceQuery RegexMatch: @"(?i)(?:^|[?&])tempauth=[^&]+" json: authMatch timeoutMs: [NSNumber numberWithInt: 100]] intValue];
if (authMatched < 0) {
NSLog(@"%@",@"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: @"graph.microsoft.com" caseSensitive: NO] == YES) && ([serviceUrl.Port intValue] == 443)) {
uploadHttp.AuthToken = [token StringOf: @"access_token"];
}
else {
CkoFileAccess *tokenFiles = [[CkoFileAccess alloc] init];
if ([tokenFiles FileExists: @"qa_data/tokens/oneDrive-sharepoint.json"] == YES) {
CkoJsonObject *sharepointToken = [[CkoJsonObject alloc] init];
sharepointToken.Strict = YES;
success = [sharepointToken LoadFile: @"qa_data/tokens/oneDrive-sharepoint.json"];
if (success != YES) {
NSLog(@"%@",@"Could not read the private SharePoint token cache.");
return;
}
if (([[sharepointToken JsonTypeOf: @"host"] intValue] != 1) || ([sharepointToken StringOfEquals: @"host" value: @"" caseSensitive: YES] == YES)) {
NSLog(@"%@",@"Expected a nonempty host in the JSON.");
return;
}
if (([[sharepointToken JsonTypeOf: @"access_token"] intValue] != 1) || ([sharepointToken StringOfEquals: @"access_token" value: @"" caseSensitive: YES] == YES)) {
NSLog(@"%@",@"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: [sharepointToken StringOf: @"host"] caseSensitive: NO] == YES) && ([serviceUrl.Port intValue] == 443)) {
uploadHttp.AuthToken = [sharepointToken StringOf: @"access_token"];
}
}
}
}
// Without a matching token, only a still-valid preauthenticated URL can succeed.
CkoDateTime *expires = [[CkoDateTime alloc] init];
CkoDateTime *now = [[CkoDateTime alloc] init];
success = [expires SetFromTimestamp: [receipt StringOf: @"expirationDateTime"]];
if (success != YES) {
NSLog(@"%@",@"Invalid session expiry.");
return;
}
success = [now SetFromCurrentSystemTime];
if (success != YES) {
NSLog(@"%@",@"Could not check the expiry.");
return;
}
if ([[expires DiffSeconds: now] intValue] <= 0) {
NSLog(@"%@",@"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.
CkoHttpResponse *uploadResp = [[CkoHttpResponse alloc] init];
CkoJsonObject *session = [[CkoJsonObject alloc] init];
session.Strict = YES;
int offset = 0;
if (resuming == YES) {
// Server status is authoritative after a lost response; a local offset might be stale.
success = [uploadHttp HttpNoBody: @"GET" url: uploadUrl response: uploadResp];
if (([uploadResp.StatusCode intValue] == 401) || ([uploadResp.StatusCode intValue] == 403)) {
NSLog(@"%@%d",@"Session authentication or permission failure. HTTP status: ",[uploadResp.StatusCode intValue]);
NSLog(@"%@",@"Refresh the correct service token or check grants, then resume this receipt. Do not recreate blindly.");
return;
}
if ((success != YES) && ([uploadResp.StatusCode intValue] == 0)) {
NSLog(@"%@",@"No HTTP response received; inspect diagnostics privately and reconcile writes before retrying.");
return;
}
if (([uploadResp.StatusCode intValue] != 200)) {
NSLog(@"%@%d",@"Unexpected HTTP status: ",[uploadResp.StatusCode intValue]);
NSLog(@"%@%@",@"Request ID: ",[uploadResp GetHeaderField: @"request-id"]);
if ([uploadResp.StatusCode intValue] == 429) {
NSLog(@"%@%@",@"Retry-After: ",[uploadResp GetHeaderField: @"Retry-After"]);
}
return;
}
success = [session Load: uploadResp.BodyStr];
if (success != YES) {
NSLog(@"%@",@"Expected a well-formed JSON response.");
return;
}
}
else {
[session UpdateString: @"nextExpectedRanges[0]" value: @"0-"];
}
CkoStringBuilder *range = [[CkoStringBuilder alloc] init];
CkoStringBuilder *contentRange = [[CkoStringBuilder alloc] init];
CkoStringBuilder *offsetText = [[CkoStringBuilder alloc] init];
CkoStringBuilder *countText = [[CkoStringBuilder alloc] init];
CkoHttpRequest *chunkRequest = [[CkoHttpRequest alloc] init];
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 SizeOfArray: @"nextExpectedRanges"] intValue] != 1) || ([[session JsonTypeOf: @"nextExpectedRanges[0]"] intValue] != 1)) {
NSLog(@"%@",@"Expected one remaining range; inspect session status before continuing.");
return;
}
[range SetString: [session StringOf: @"nextExpectedRanges[0]"]];
matched = [[range RegexMatch: @"\\A[0-9]{1,9}-\\z" json: match timeoutMs: [NSNumber numberWithInt: 100]] intValue];
if (matched != 1) {
NSLog(@"%@",@"Expected a single open-ended offset such as 3276800-; no more bytes sent.");
return;
}
int replacements = [[range Replace: @"-" replacement: @""] intValue];
int nextOffset = [range.IntValue intValue];
if ((nextOffset < offset) || (nextOffset >= fileSize)) {
NSLog(@"%@",@"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.
int chunkSize = 10485760;
if ((fileSize - offset) < chunkSize) {
chunkSize = fileSize - offset;
}
int endByte = offset + chunkSize - 1;
[offsetText Clear];
[offsetText AppendInt: [NSNumber numberWithInt: offset]];
[countText Clear];
[countText AppendInt: [NSNumber numberWithInt: chunkSize]];
success = [chunkRequest StreamChunkFromFile: filePath offset: [offsetText GetAsString] numBytes: [countText GetAsString]];
if (success != YES) {
NSLog(@"%@",@"Could not prepare the file chunk.");
return;
}
[contentRange SetString: @"bytes "];
[contentRange AppendInt: [NSNumber numberWithInt: offset]];
[contentRange Append: @"-"];
[contentRange AppendInt: [NSNumber numberWithInt: endByte]];
[contentRange Append: @"/"];
[contentRange AppendInt: [NSNumber numberWithInt: fileSize]];
[chunkRequest AddHeader: @"Content-Range" value: [contentRange GetAsString]];
success = [uploadHttp HttpReq: uploadUrl request: chunkRequest response: uploadResp];
if (([uploadResp.StatusCode intValue] == 401) || ([uploadResp.StatusCode intValue] == 403)) {
NSLog(@"%@%d",@"Session authentication or permission failure. HTTP status: ",[uploadResp.StatusCode intValue]);
NSLog(@"%@",@"Refresh the correct service token or check grants, then resume this receipt. Do not recreate blindly.");
return;
}
if ((success != YES) && ([uploadResp.StatusCode intValue] == 0)) {
NSLog(@"%@",@"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) {
NSLog(@"%@",@"Unexpected early completion; reconcile the target.");
return;
}
success = [result Load: uploadResp.BodyStr];
if (success != YES) {
NSLog(@"%@",@"Upload may have completed but its response is invalid; reconcile before retrying.");
return;
}
if (([[result JsonTypeOf: @"id"] intValue] != 1) || ([result StringOfEquals: @"id" value: @"" caseSensitive: YES] == YES)) {
NSLog(@"%@",@"Expected a nonempty id in the JSON.");
return;
}
[receipt UpdateString: @"status" value: @"complete"];
[receipt UpdateString: @"itemId" value: [result StringOf: @"id"]];
success = [receipt WriteFile: receiptPath];
if (success != YES) {
NSLog(@"%@",@"Upload completed but saving its ID failed; reconcile before retrying.");
return;
}
NSLog(@"%@%@",@"Upload completed. Item ID: ",[result StringOf: @"id"]);
return;
}
if ((success != YES) && ([uploadResp.StatusCode intValue] == 0)) {
NSLog(@"%@",@"No HTTP response received; inspect diagnostics privately and reconcile writes before retrying.");
return;
}
if (([uploadResp.StatusCode intValue] != 202)) {
NSLog(@"%@%d",@"Unexpected HTTP status: ",[uploadResp.StatusCode intValue]);
NSLog(@"%@%@",@"Request ID: ",[uploadResp GetHeaderField: @"request-id"]);
if ([uploadResp.StatusCode intValue] == 429) {
NSLog(@"%@%@",@"Retry-After: ",[uploadResp GetHeaderField: @"Retry-After"]);
}
return;
}
success = [session Load: uploadResp.BodyStr];
if (success != YES) {
NSLog(@"%@",@"Expected a well-formed JSON response.");
return;
}
if ((endByte + 1) == fileSize) {
NSLog(@"%@",@"Final bytes returned 202, not a completed item. Retain the session and inspect its status.");
return;
}
offset = endByte + 1;
if (([[session JsonTypeOf: @"expirationDateTime"] intValue] != 1) || ([session StringOfEquals: @"expirationDateTime" value: @"" caseSensitive: YES] == YES)) {
NSLog(@"%@",@"Expected a nonempty expirationDateTime in the JSON.");
return;
}
[receipt UpdateString: @"expirationDateTime" value: [session StringOf: @"expirationDateTime"]];
[receipt UpdateInt: @"confirmedOffset" value: [NSNumber numberWithInt: offset]];
success = [receipt WriteFile: receiptPath];
if (success != YES) {
NSLog(@"%@",@"Could not checkpoint progress; retain the prior receipt and query the server on resume.");
return;
}
NSLog(@"%@%d",@"Uploaded bytes so far: ",offset);
}