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 Lazarus Pascal Downloads
program ChilkatDemo;
// Demonstrates using the Chilkat Pascal wrapper via the C bridge DLL.
// Builds as a console application under Lazarus (FPC) or Delphi.
{$IFDEF FPC}
{$MODE DELPHI}
{$ENDIF}
{$APPTYPE CONSOLE}
uses
{$IFDEF UNIX}
cthreads,
{$ENDIF}
SysUtils,
CkDllLoader,
Chilkat.CkDateTime,
Chilkat.Url,
Chilkat.FileAccess,
Chilkat.HttpResponse,
Chilkat.StringBuilder,
Chilkat.JsonObject,
Chilkat.Crypt2,
Chilkat.HttpRequest,
Chilkat.Http;
// ---------------------------------------------------------------------------
procedure RunDemo;
var
success: Boolean;
token: TJsonObject;
http: THttp;
resp: THttpResponse;
result: TJsonObject;
driveId: string;
parentId: string;
fileName: string;
filePath: string;
receiptPath: string;
fac: TFileAccess;
sizeString: string;
sizeText: TStringBuilder;
match: TJsonObject;
matched: Integer;
fileSize: Integer;
hash: TCrypt2;
fileHash: string;
receipt: TJsonObject;
resuming: Boolean;
endpoint: TStringBuilder;
body: TJsonObject;
uploadUrl: string;
serviceUrl: TUrl;
uploadHttp: THttp;
serviceHost: TStringBuilder;
serviceQuery: TStringBuilder;
authMatch: TJsonObject;
authMatched: Integer;
tokenFiles: TFileAccess;
sharepointToken: TJsonObject;
expires: TCkDateTime;
now: TCkDateTime;
uploadResp: THttpResponse;
session: TJsonObject;
offset: Integer;
range: TStringBuilder;
contentRange: TStringBuilder;
offsetText: TStringBuilder;
countText: TStringBuilder;
chunkRequest: THttpRequest;
replacements: Integer;
nextOffset: Integer;
chunkSize: Integer;
endByte: Integer;
begin
success := 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.
token := TJsonObject.Create;
token.Strict := True;
success := token.LoadFile('qa_data/tokens/oneDrive.json');
if (success <> True) then
begin
WriteLn('Could not load the private OneDrive token cache.');
Exit;
end;
if ((token.JsonTypeOf('access_token') <> 1) or (token.StringOfEquals('access_token','',True) = True)) then
begin
WriteLn('Expected a nonempty access_token in the JSON.');
Exit;
end;
http := THttp.Create;
http.AuthToken := token.StringOf('access_token');
http.RequireSslCertVerify := True;
http.FollowRedirects := False;
http.ConnectTimeout := 20;
http.ReadTimeout := 120;
http.SetRequestHeader('Accept','application/json');
resp := THttpResponse.Create;
result := TJsonObject.Create;
result.Strict := True;
driveId := 'YOUR_DRIVE_ID';
parentId := 'YOUR_PARENT_FOLDER_ID';
fileName := 'large.bin';
filePath := 'qa_data/large/sample.bin';
receiptPath := 'qa_data/oneDrive/upload-session.json';
fac := TFileAccess.Create;
sizeString := fac.FileSizeStr(filePath);
if (fac.LastMethodSuccess <> True) then
begin
WriteLn('Could not determine the source file size.');
Exit;
end;
sizeText := TStringBuilder.Create;
sizeText.Append(sizeString);
match := TJsonObject.Create;
matched := sizeText.RegexMatch('\A[0-9]{1,9}\z',match,100);
if (matched <> 1) then
begin
WriteLn('File size exceeds this example''s supported range.');
Exit;
end;
fileSize := sizeText.IntValue;
if ((fileSize < 1) or (fileSize > 999999999)) then
begin
WriteLn('This example supports nonempty files up to 999,999,999 bytes; its int arithmetic is deliberately bounded.');
Exit;
end;
success := fac.DirEnsureExists('qa_data/oneDrive');
if (success <> True) then
begin
WriteLn('Could not create the private receipt directory.');
Exit;
end;
hash := TCrypt2.Create;
hash.HashAlgorithm := 'sha256';
hash.EncodingMode := 'hex';
fileHash := hash.HashFileENC(filePath);
if (hash.LastMethodSuccess <> True) then
begin
WriteLn('Could not fingerprint the source file.');
Exit;
end;
receipt := TJsonObject.Create;
receipt.Strict := True;
resuming := fac.FileExists(receiptPath);
if (resuming = True) then
begin
success := receipt.LoadFile(receiptPath);
if (success <> True) then
begin
WriteLn('Invalid receipt; reconcile the target before another upload.');
Exit;
end;
if ((receipt.StringOfEquals('driveId',driveId,True) <> True) or (receipt.StringOfEquals('parentId',parentId,True) <> True) or (receipt.StringOfEquals('name',fileName,True) <> True) or (receipt.StringOfEquals('fileHash',fileHash,True) <> True) or (receipt.IntOf('fileSize') <> fileSize)) then
begin
WriteLn('Receipt does not match the drive, parent, name, and file; no request sent.');
Exit;
end;
if (receipt.StringOfEquals('status','complete',True) = True) then
begin
WriteLn('Already uploaded. Item ID: ' + receipt.StringOf('itemId'));
Exit;
end;
if (receipt.StringOfEquals('status','uploading',True) <> True) then
begin
WriteLn('Previous session creation is uncertain; inspect the pending receipt before retrying.');
Exit;
end;
if ((receipt.JsonTypeOf('uploadUrl') <> 1) or (receipt.StringOfEquals('uploadUrl','',True) = True)) then
begin
WriteLn('Expected a nonempty uploadUrl in the JSON.');
Exit;
end;
if ((receipt.JsonTypeOf('expirationDateTime') <> 1) or (receipt.StringOfEquals('expirationDateTime','',True) = True)) then
begin
WriteLn('Expected a nonempty expirationDateTime in the JSON.');
Exit;
end;
end
else
begin
endpoint := TStringBuilder.Create;
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');
body := TJsonObject.Create;
body.UpdateString('item.name',fileName);
body.UpdateString('item."@microsoft.graph.conflictBehavior"','fail');
receipt.UpdateString('driveId',driveId);
receipt.UpdateString('parentId',parentId);
receipt.UpdateString('name',fileName);
receipt.UpdateString('fileHash',fileHash);
receipt.UpdateInt('fileSize',fileSize);
receipt.UpdateString('status','pending');
success := receipt.WriteFile(receiptPath);
if (success <> True) then
begin
WriteLn('Could not save the pending receipt; no session created.');
Exit;
end;
success := http.HttpJson('POST',endpoint.GetAsString(),body,'application/json',resp);
if ((success <> True) and (resp.StatusCode = 0)) then
begin
WriteLn('No HTTP response received; inspect diagnostics privately and reconcile writes before retrying.');
Exit;
end;
if ((resp.StatusCode <> 200)) then
begin
WriteLn('Unexpected HTTP status: ' + resp.StatusCode);
WriteLn('Request ID: ' + resp.GetHeaderField('request-id'));
if (resp.StatusCode = 429) then
begin
WriteLn('Retry-After: ' + resp.GetHeaderField('Retry-After'));
end;
Exit;
end;
success := result.Load(resp.BodyStr);
if (success <> True) then
begin
WriteLn('Expected a well-formed JSON response.');
Exit;
end;
if ((result.JsonTypeOf('uploadUrl') <> 1) or (result.StringOfEquals('uploadUrl','',True) = True)) then
begin
WriteLn('Expected a nonempty uploadUrl in the JSON.');
Exit;
end;
if ((result.JsonTypeOf('expirationDateTime') <> 1) or (result.StringOfEquals('expirationDateTime','',True) = True)) then
begin
WriteLn('Expected a nonempty expirationDateTime in the JSON.');
Exit;
end;
receipt.UpdateString('uploadUrl',result.StringOf('uploadUrl'));
receipt.UpdateString('expirationDateTime',result.StringOf('expirationDateTime'));
receipt.UpdateString('status','uploading');
success := receipt.WriteFile(receiptPath);
if (success <> True) then
begin
WriteLn('Session created but receipt save failed; reconcile before another creation.');
Exit;
end;
end;
uploadUrl := receipt.StringOf('uploadUrl');
serviceUrl := TUrl.Create;
success := serviceUrl.ParseUrl(uploadUrl);
if (success <> True) then
begin
WriteLn('Invalid returned service URL.');
Exit;
end;
if ((serviceUrl.Ssl <> True) or (serviceUrl.Host = '') or (serviceUrl.Login <> '') or (serviceUrl.Password <> '')) then
begin
WriteLn('Expected an HTTPS service URL without embedded login credentials.');
Exit;
end;
// Returned URLs can be preauthenticated, Graph-authenticated, or SharePoint-authenticated.
// Never copy Graph authorization to an arbitrary host, and never follow redirects automatically.
uploadHttp := THttp.Create;
uploadHttp.RequireSslCertVerify := True;
uploadHttp.FollowRedirects := False;
uploadHttp.ConnectTimeout := 20;
uploadHttp.ReadTimeout := 120;
serviceHost := TStringBuilder.Create;
serviceHost.Append(serviceUrl.Host);
serviceQuery := TStringBuilder.Create;
serviceQuery.Append(serviceUrl.Query);
authMatch := TJsonObject.Create;
authMatched := serviceQuery.RegexMatch('(?i)(?:^|[?&])tempauth=[^&]+',authMatch,100);
if (authMatched < 0) then
begin
WriteLn('Could not inspect the service URL query.');
Exit;
end;
// tempauth carries its own authorization. Do not add a bearer token to that legacy URL.
if (authMatched = 0) then
begin
if ((serviceHost.ContentsEqual('graph.microsoft.com',False) = True) and (serviceUrl.Port = 443)) then
begin
uploadHttp.AuthToken := token.StringOf('access_token');
end
else
begin
tokenFiles := TFileAccess.Create;
if (tokenFiles.FileExists('qa_data/tokens/oneDrive-sharepoint.json') = True) then
begin
sharepointToken := TJsonObject.Create;
sharepointToken.Strict := True;
success := sharepointToken.LoadFile('qa_data/tokens/oneDrive-sharepoint.json');
if (success <> True) then
begin
WriteLn('Could not read the private SharePoint token cache.');
Exit;
end;
if ((sharepointToken.JsonTypeOf('host') <> 1) or (sharepointToken.StringOfEquals('host','',True) = True)) then
begin
WriteLn('Expected a nonempty host in the JSON.');
Exit;
end;
if ((sharepointToken.JsonTypeOf('access_token') <> 1) or (sharepointToken.StringOfEquals('access_token','',True) = True)) then
begin
WriteLn('Expected a nonempty access_token in the JSON.');
Exit;
end;
// Configure host independently; never trust a response URL to choose a new credential audience.
if ((serviceHost.ContentsEqual(sharepointToken.StringOf('host'),False) = True) and (serviceUrl.Port = 443)) then
begin
uploadHttp.AuthToken := sharepointToken.StringOf('access_token');
end;
end;
end;
end;
// Without a matching token, only a still-valid preauthenticated URL can succeed.
expires := TCkDateTime.Create;
now := TCkDateTime.Create;
success := expires.SetFromTimestamp(receipt.StringOf('expirationDateTime'));
if (success <> True) then
begin
WriteLn('Invalid session expiry.');
Exit;
end;
success := now.SetFromCurrentSystemTime();
if (success <> True) then
begin
WriteLn('Could not check the expiry.');
Exit;
end;
if (expires.DiffSeconds(now) <= 0) then
begin
WriteLn('Session expired. Reconcile the destination before creating a replacement.');
Exit;
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.
uploadResp := THttpResponse.Create;
session := TJsonObject.Create;
session.Strict := True;
offset := 0;
if (resuming = True) then
begin
// Server status is authoritative after a lost response; a local offset might be stale.
success := uploadHttp.HttpNoBody('GET',uploadUrl,uploadResp);
if ((uploadResp.StatusCode = 401) or (uploadResp.StatusCode = 403)) then
begin
WriteLn('Session authentication or permission failure. HTTP status: ' + uploadResp.StatusCode);
WriteLn('Refresh the correct service token or check grants, then resume this receipt. Do not recreate blindly.');
Exit;
end;
if ((success <> True) and (uploadResp.StatusCode = 0)) then
begin
WriteLn('No HTTP response received; inspect diagnostics privately and reconcile writes before retrying.');
Exit;
end;
if ((uploadResp.StatusCode <> 200)) then
begin
WriteLn('Unexpected HTTP status: ' + uploadResp.StatusCode);
WriteLn('Request ID: ' + uploadResp.GetHeaderField('request-id'));
if (uploadResp.StatusCode = 429) then
begin
WriteLn('Retry-After: ' + uploadResp.GetHeaderField('Retry-After'));
end;
Exit;
end;
success := session.Load(uploadResp.BodyStr);
if (success <> True) then
begin
WriteLn('Expected a well-formed JSON response.');
Exit;
end;
end
else
begin
session.UpdateString('nextExpectedRanges[0]','0-');
end;
range := TStringBuilder.Create;
contentRange := TStringBuilder.Create;
offsetText := TStringBuilder.Create;
countText := TStringBuilder.Create;
chunkRequest := THttpRequest.Create;
chunkRequest.HttpVerb := 'PUT';
chunkRequest.ContentType := 'application/octet-stream';
while (offset < fileSize) do
begin
// This sequential example handles a single open-ended remaining range.
// Stop rather than misinterpreting multiple holes or a bounded range.
if ((session.SizeOfArray('nextExpectedRanges') <> 1) or (session.JsonTypeOf('nextExpectedRanges[0]') <> 1)) then
begin
WriteLn('Expected one remaining range; inspect session status before continuing.');
Exit;
end;
range.SetString(session.StringOf('nextExpectedRanges[0]'));
matched := range.RegexMatch('\A[0-9]{1,9}-\z',match,100);
if (matched <> 1) then
begin
WriteLn('Expected a single open-ended offset such as 3276800-; no more bytes sent.');
Exit;
end;
replacements := range.Replace('-','');
nextOffset := range.IntValue;
if ((nextOffset < offset) or (nextOffset >= fileSize)) then
begin
WriteLn('Unexpected server offset; retain the receipt and reconcile.');
Exit;
end;
offset := nextOffset;
// 10 MiB is 32 * 320 KiB and is below the 60 MiB per-request limit.
chunkSize := 10485760;
if ((fileSize - offset) < chunkSize) then
begin
chunkSize := fileSize - offset;
end;
endByte := offset + chunkSize - 1;
offsetText.Clear();
offsetText.AppendInt(offset);
countText.Clear();
countText.AppendInt(chunkSize);
success := chunkRequest.StreamChunkFromFile(filePath,offsetText.GetAsString(),countText.GetAsString());
if (success <> True) then
begin
WriteLn('Could not prepare the file chunk.');
Exit;
end;
contentRange.SetString('bytes ');
contentRange.AppendInt(offset);
contentRange.Append('-');
contentRange.AppendInt(endByte);
contentRange.Append('/');
contentRange.AppendInt(fileSize);
chunkRequest.AddHeader('Content-Range',contentRange.GetAsString());
success := uploadHttp.HttpReq(uploadUrl,chunkRequest,uploadResp);
if ((uploadResp.StatusCode = 401) or (uploadResp.StatusCode = 403)) then
begin
WriteLn('Session authentication or permission failure. HTTP status: ' + uploadResp.StatusCode);
WriteLn('Refresh the correct service token or check grants, then resume this receipt. Do not recreate blindly.');
Exit;
end;
if ((success <> True) and (uploadResp.StatusCode = 0)) then
begin
WriteLn('Upload response lost. Retain this receipt and query the session on the next run.');
Exit;
end;
if ((uploadResp.StatusCode = 200) or (uploadResp.StatusCode = 201)) then
begin
if ((endByte + 1) <> fileSize) then
begin
WriteLn('Unexpected early completion; reconcile the target.');
Exit;
end;
success := result.Load(uploadResp.BodyStr);
if (success <> True) then
begin
WriteLn('Upload may have completed but its response is invalid; reconcile before retrying.');
Exit;
end;
if ((result.JsonTypeOf('id') <> 1) or (result.StringOfEquals('id','',True) = True)) then
begin
WriteLn('Expected a nonempty id in the JSON.');
Exit;
end;
receipt.UpdateString('status','complete');
receipt.UpdateString('itemId',result.StringOf('id'));
success := receipt.WriteFile(receiptPath);
if (success <> True) then
begin
WriteLn('Upload completed but saving its ID failed; reconcile before retrying.');
Exit;
end;
WriteLn('Upload completed. Item ID: ' + result.StringOf('id'));
Exit;
end;
if ((success <> True) and (uploadResp.StatusCode = 0)) then
begin
WriteLn('No HTTP response received; inspect diagnostics privately and reconcile writes before retrying.');
Exit;
end;
if ((uploadResp.StatusCode <> 202)) then
begin
WriteLn('Unexpected HTTP status: ' + uploadResp.StatusCode);
WriteLn('Request ID: ' + uploadResp.GetHeaderField('request-id'));
if (uploadResp.StatusCode = 429) then
begin
WriteLn('Retry-After: ' + uploadResp.GetHeaderField('Retry-After'));
end;
Exit;
end;
success := session.Load(uploadResp.BodyStr);
if (success <> True) then
begin
WriteLn('Expected a well-formed JSON response.');
Exit;
end;
if ((endByte + 1) = fileSize) then
begin
WriteLn('Final bytes returned 202, not a completed item. Retain the session and inspect its status.');
Exit;
end;
offset := endByte + 1;
if ((session.JsonTypeOf('expirationDateTime') <> 1) or (session.StringOfEquals('expirationDateTime','',True) = True)) then
begin
WriteLn('Expected a nonempty expirationDateTime in the JSON.');
Exit;
end;
receipt.UpdateString('expirationDateTime',session.StringOf('expirationDateTime'));
receipt.UpdateInt('confirmedOffset',offset);
success := receipt.WriteFile(receiptPath);
if (success <> True) then
begin
WriteLn('Could not checkpoint progress; retain the prior receipt and query the server on resume.');
Exit;
end;
WriteLn('Uploaded bytes so far: ' + offset);
end;
token.Free;
http.Free;
resp.Free;
result.Free;
fac.Free;
sizeText.Free;
match.Free;
hash.Free;
receipt.Free;
endpoint.Free;
body.Free;
serviceUrl.Free;
uploadHttp.Free;
serviceHost.Free;
serviceQuery.Free;
authMatch.Free;
tokenFiles.Free;
sharepointToken.Free;
expires.Free;
now.Free;
uploadResp.Free;
session.Free;
range.Free;
contentRange.Free;
offsetText.Free;
countText.Free;
chunkRequest.Free;
end;
// ---------------------------------------------------------------------------
begin
try
RunDemo;
except
on E: Exception do
WriteLn('Unhandled exception: ', E.ClassName, ': ', E.Message);
end;
WriteLn;
{$IFDEF MSWINDOWS}
WriteLn('Press Enter to exit...');
ReadLn;
{$ENDIF}
end.