OneDrive: Download a File to Disk
See more OneDrive Examples
GET /content can return HTTP 200 with file bytes directly, or HTTP 302 with a service URL. Handle both instead of requiring a redirect. Check transport completion and HTTP status, and compare Content-Length to the received byte count when supplied. Requests specify identity encoding; unexpected content encodings are rejected. A successful zero-byte file is valid. A 401 can mean an expired token, wrong audience, or expired preauthenticated URL; a 403 can indicate missing grants or policy restrictions.
Both the initial Graph request and any returned-URL request use HttpReq with Http.StreamResponseBodyPath to stream into a generated .part file. The redirect body is replaced by the actual content. Rename only after a complete HTTP 200 transfer, so errors and truncated responses never become the final file. A failed transfer may leave a private .part file for cleanup. The file content is not buffered in memory and supplied remote filenames are not used as local paths.
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.
Permission: Files.Read.
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 Visual FoxPro Downloads
LOCAL lnSuccess
LOCAL loToken
LOCAL loHttp
LOCAL loResp
LOCAL loResult
LOCAL lcDriveId
LOCAL lcItemId
LOCAL loEndpoint
LOCAL loFac
LOCAL loUuid
LOCAL lcLocalId
LOCAL loTarget
LOCAL lcFinalPath
LOCAL lcPartialPath
LOCAL loStreamRequest
LOCAL lcDownloadUrl
LOCAL loServiceUrl
LOCAL loDownloadHttp
LOCAL loServiceHost
LOCAL loServiceQuery
LOCAL loAuthMatch
LOCAL lnAuthMatched
LOCAL loTokenFiles
LOCAL loSharepointToken
LOCAL lcActualSize
LOCAL loContentEncoding
LOCAL loDeclaredLength
LOCAL loLengthMatch
LOCAL lnLengthMatched
lnSuccess = 0
* Assumes Chilkat is unlocked. See Global Unlock Sample.
lnSuccess = 0
* Obtain a delegated Graph token with this example's file permissions.
* See OneDrive OAuth2 with PKCE.
loToken = CreateObject('Chilkat.JsonObject')
loToken.Strict = 1
lnSuccess = loToken.LoadFile("qa_data/tokens/oneDrive.json")
IF (lnSuccess <> 1) THEN
? "Could not load the private OneDrive token cache."
RELEASE loToken
CANCEL
ENDIF
IF ((loToken.JsonTypeOf("access_token") <> 1) OR (loToken.StringOfEquals("access_token","",1) = 1)) THEN
? "Expected a nonempty access_token in the JSON."
RELEASE loToken
CANCEL
ENDIF
loHttp = CreateObject('Chilkat.Http')
loHttp.AuthToken = loToken.StringOf("access_token")
loHttp.RequireSslCertVerify = 1
loHttp.FollowRedirects = 0
loHttp.ConnectTimeout = 20
loHttp.ReadTimeout = 120
loHttp.SetRequestHeader("Accept","application/json")
loResp = CreateObject('Chilkat.HttpResponse')
loResult = CreateObject('Chilkat.JsonObject')
loResult.Strict = 1
lcDriveId = "YOUR_DRIVE_ID"
lcItemId = "YOUR_ITEM_ID"
loEndpoint = CreateObject('Chilkat.StringBuilder')
loEndpoint.Append("https://graph.microsoft.com/v1.0/drives/")
loEndpoint.Append(loHttp.UrlEncode(lcDriveId))
loEndpoint.Append("/items/")
loEndpoint.Append(loHttp.UrlEncode(lcItemId))
loEndpoint.Append("/content")
loHttp.SetRequestHeader("Accept","*/*")
loHttp.SetRequestHeader("Accept-Encoding","identity")
loFac = CreateObject('Chilkat.FileAccess')
lnSuccess = loFac.DirEnsureExists("qa_output/oneDrive")
IF (lnSuccess <> 1) THEN
? "Could not create the output directory."
RELEASE loToken
RELEASE loHttp
RELEASE loResp
RELEASE loResult
RELEASE loEndpoint
RELEASE loFac
CANCEL
ENDIF
loUuid = CreateObject('Chilkat.Crypt2')
lcLocalId = loUuid.GenerateUuid()
IF (loUuid.LastMethodSuccess <> 1) THEN
? "Could not make a local filename."
RELEASE loToken
RELEASE loHttp
RELEASE loResp
RELEASE loResult
RELEASE loEndpoint
RELEASE loFac
RELEASE loUuid
CANCEL
ENDIF
loTarget = CreateObject('Chilkat.StringBuilder')
loTarget.Append("qa_output/oneDrive/")
loTarget.Append(lcLocalId)
loTarget.Append(".bin")
lcFinalPath = loTarget.GetAsString()
loTarget.Append(".part")
lcPartialPath = loTarget.GetAsString()
IF (loFac.FileExists(lcFinalPath) OR loFac.FileExists(lcPartialPath)) THEN
? "A generated output path already exists; nothing overwritten."
RELEASE loToken
RELEASE loHttp
RELEASE loResp
RELEASE loResult
RELEASE loEndpoint
RELEASE loFac
RELEASE loUuid
RELEASE loTarget
CANCEL
ENDIF
* Stream even the initial Graph response; direct content can be arbitrarily large.
loStreamRequest = CreateObject('Chilkat.HttpRequest')
loStreamRequest.HttpVerb = "GET"
loHttp.StreamResponseBodyPath = lcPartialPath
lnSuccess = loHttp.HttpReq(loEndpoint.GetAsString(),loStreamRequest,loResp)
loHttp.StreamResponseBodyPath = ""
IF ((lnSuccess <> 1) AND (loResp.StatusCode = 0)) THEN
? "No HTTP response received; inspect diagnostics privately and reconcile writes before retrying."
RELEASE loToken
RELEASE loHttp
RELEASE loResp
RELEASE loResult
RELEASE loEndpoint
RELEASE loFac
RELEASE loUuid
RELEASE loTarget
RELEASE loStreamRequest
CANCEL
ENDIF
IF ((loResp.StatusCode <> 200) AND (loResp.StatusCode <> 302)) THEN
? "Unexpected HTTP status: " + STR(loResp.StatusCode)
? "Request ID: " + loResp.GetHeaderField("request-id")
IF (loResp.StatusCode = 429) THEN
? "Retry-After: " + loResp.GetHeaderField("Retry-After")
ENDIF
RELEASE loToken
RELEASE loHttp
RELEASE loResp
RELEASE loResult
RELEASE loEndpoint
RELEASE loFac
RELEASE loUuid
RELEASE loTarget
RELEASE loStreamRequest
CANCEL
ENDIF
IF (loResp.StatusCode = 302) THEN
lcDownloadUrl = loResp.GetHeaderField("Location")
loServiceUrl = CreateObject('Chilkat.Url')
lnSuccess = loServiceUrl.ParseUrl(lcDownloadUrl)
IF (lnSuccess <> 1) THEN
? "Invalid returned service URL."
RELEASE loToken
RELEASE loHttp
RELEASE loResp
RELEASE loResult
RELEASE loEndpoint
RELEASE loFac
RELEASE loUuid
RELEASE loTarget
RELEASE loStreamRequest
RELEASE loServiceUrl
CANCEL
ENDIF
IF ((loServiceUrl.Ssl <> 1) OR (loServiceUrl.Host = "") OR (loServiceUrl.Login <> "") OR (loServiceUrl.Password <> "")) THEN
? "Expected an HTTPS service URL without embedded login credentials."
RELEASE loToken
RELEASE loHttp
RELEASE loResp
RELEASE loResult
RELEASE loEndpoint
RELEASE loFac
RELEASE loUuid
RELEASE loTarget
RELEASE loStreamRequest
RELEASE loServiceUrl
CANCEL
ENDIF
* Returned URLs can be preauthenticated, Graph-authenticated, or SharePoint-authenticated.
* Never copy Graph authorization to an arbitrary host, and never follow redirects automatically.
loDownloadHttp = CreateObject('Chilkat.Http')
loDownloadHttp.RequireSslCertVerify = 1
loDownloadHttp.FollowRedirects = 0
loDownloadHttp.ConnectTimeout = 20
loDownloadHttp.ReadTimeout = 120
loServiceHost = CreateObject('Chilkat.StringBuilder')
loServiceHost.Append(loServiceUrl.Host)
loServiceQuery = CreateObject('Chilkat.StringBuilder')
loServiceQuery.Append(loServiceUrl.Query)
loAuthMatch = CreateObject('Chilkat.JsonObject')
lnAuthMatched = loServiceQuery.RegexMatch("(?i)(?:^|[?&])tempauth=[^&]+",loAuthMatch,100)
IF (lnAuthMatched < 0) THEN
? "Could not inspect the service URL query."
RELEASE loToken
RELEASE loHttp
RELEASE loResp
RELEASE loResult
RELEASE loEndpoint
RELEASE loFac
RELEASE loUuid
RELEASE loTarget
RELEASE loStreamRequest
RELEASE loServiceUrl
RELEASE loDownloadHttp
RELEASE loServiceHost
RELEASE loServiceQuery
RELEASE loAuthMatch
CANCEL
ENDIF
* tempauth carries its own authorization. Do not add a bearer token to that legacy URL.
IF (lnAuthMatched = 0) THEN
IF ((loServiceHost.ContentsEqual("graph.microsoft.com",0) = 1) AND (loServiceUrl.Port = 443)) THEN
loDownloadHttp.AuthToken = loToken.StringOf("access_token")
ELSE
loTokenFiles = CreateObject('Chilkat.FileAccess')
IF (loTokenFiles.FileExists("qa_data/tokens/oneDrive-sharepoint.json") = 1) THEN
loSharepointToken = CreateObject('Chilkat.JsonObject')
loSharepointToken.Strict = 1
lnSuccess = loSharepointToken.LoadFile("qa_data/tokens/oneDrive-sharepoint.json")
IF (lnSuccess <> 1) THEN
? "Could not read the private SharePoint token cache."
RELEASE loToken
RELEASE loHttp
RELEASE loResp
RELEASE loResult
RELEASE loEndpoint
RELEASE loFac
RELEASE loUuid
RELEASE loTarget
RELEASE loStreamRequest
RELEASE loServiceUrl
RELEASE loDownloadHttp
RELEASE loServiceHost
RELEASE loServiceQuery
RELEASE loAuthMatch
RELEASE loTokenFiles
RELEASE loSharepointToken
CANCEL
ENDIF
IF ((loSharepointToken.JsonTypeOf("host") <> 1) OR (loSharepointToken.StringOfEquals("host","",1) = 1)) THEN
? "Expected a nonempty host in the JSON."
RELEASE loToken
RELEASE loHttp
RELEASE loResp
RELEASE loResult
RELEASE loEndpoint
RELEASE loFac
RELEASE loUuid
RELEASE loTarget
RELEASE loStreamRequest
RELEASE loServiceUrl
RELEASE loDownloadHttp
RELEASE loServiceHost
RELEASE loServiceQuery
RELEASE loAuthMatch
RELEASE loTokenFiles
RELEASE loSharepointToken
CANCEL
ENDIF
IF ((loSharepointToken.JsonTypeOf("access_token") <> 1) OR (loSharepointToken.StringOfEquals("access_token","",1) = 1)) THEN
? "Expected a nonempty access_token in the JSON."
RELEASE loToken
RELEASE loHttp
RELEASE loResp
RELEASE loResult
RELEASE loEndpoint
RELEASE loFac
RELEASE loUuid
RELEASE loTarget
RELEASE loStreamRequest
RELEASE loServiceUrl
RELEASE loDownloadHttp
RELEASE loServiceHost
RELEASE loServiceQuery
RELEASE loAuthMatch
RELEASE loTokenFiles
RELEASE loSharepointToken
CANCEL
ENDIF
* Configure host independently; never trust a response URL to choose a new credential audience.
IF ((loServiceHost.ContentsEqual(loSharepointToken.StringOf("host"),0) = 1) AND (loServiceUrl.Port = 443)) THEN
loDownloadHttp.AuthToken = loSharepointToken.StringOf("access_token")
ENDIF
ENDIF
ENDIF
ENDIF
* Without a matching token, only a still-valid preauthenticated URL can succeed.
loDownloadHttp.SetRequestHeader("Accept","*/*")
loDownloadHttp.SetRequestHeader("Accept-Encoding","identity")
* The second response overwrites the temporary redirect body; it is not appended.
loDownloadHttp.StreamResponseBodyPath = lcPartialPath
lnSuccess = loDownloadHttp.HttpReq(lcDownloadUrl,loStreamRequest,loResp)
loDownloadHttp.StreamResponseBodyPath = ""
IF ((lnSuccess <> 1) AND (loResp.StatusCode = 0)) THEN
? "No HTTP response received; inspect diagnostics privately and reconcile writes before retrying."
RELEASE loToken
RELEASE loHttp
RELEASE loResp
RELEASE loResult
RELEASE loEndpoint
RELEASE loFac
RELEASE loUuid
RELEASE loTarget
RELEASE loStreamRequest
RELEASE loServiceUrl
RELEASE loDownloadHttp
RELEASE loServiceHost
RELEASE loServiceQuery
RELEASE loAuthMatch
RELEASE loTokenFiles
RELEASE loSharepointToken
CANCEL
ENDIF
IF ((loResp.StatusCode <> 200)) THEN
? "Unexpected HTTP status: " + STR(loResp.StatusCode)
? "Request ID: " + loResp.GetHeaderField("request-id")
IF (loResp.StatusCode = 429) THEN
? "Retry-After: " + loResp.GetHeaderField("Retry-After")
ENDIF
RELEASE loToken
RELEASE loHttp
RELEASE loResp
RELEASE loResult
RELEASE loEndpoint
RELEASE loFac
RELEASE loUuid
RELEASE loTarget
RELEASE loStreamRequest
RELEASE loServiceUrl
RELEASE loDownloadHttp
RELEASE loServiceHost
RELEASE loServiceQuery
RELEASE loAuthMatch
RELEASE loTokenFiles
RELEASE loSharepointToken
CANCEL
ENDIF
ENDIF
* A partial transfer can have status 200 but a false transport result. Never publish its bytes.
IF (lnSuccess <> 1) THEN
? "Content transfer did not complete; do not use its partial data."
RELEASE loToken
RELEASE loHttp
RELEASE loResp
RELEASE loResult
RELEASE loEndpoint
RELEASE loFac
RELEASE loUuid
RELEASE loTarget
RELEASE loStreamRequest
RELEASE loServiceUrl
RELEASE loDownloadHttp
RELEASE loServiceHost
RELEASE loServiceQuery
RELEASE loAuthMatch
RELEASE loTokenFiles
RELEASE loSharepointToken
CANCEL
ENDIF
lcActualSize = loFac.FileSizeStr(lcPartialPath)
IF (loFac.LastMethodSuccess <> 1) THEN
? "Could not determine the downloaded file size."
RELEASE loToken
RELEASE loHttp
RELEASE loResp
RELEASE loResult
RELEASE loEndpoint
RELEASE loFac
RELEASE loUuid
RELEASE loTarget
RELEASE loStreamRequest
RELEASE loServiceUrl
RELEASE loDownloadHttp
RELEASE loServiceHost
RELEASE loServiceQuery
RELEASE loAuthMatch
RELEASE loTokenFiles
RELEASE loSharepointToken
CANCEL
ENDIF
* Ask for identity encoding so Content-Length can be compared to the stored file bytes.
loContentEncoding = CreateObject('Chilkat.StringBuilder')
loContentEncoding.Append(loResp.GetHeaderField("Content-Encoding"))
loContentEncoding.Trim()
IF ((loContentEncoding.Length > 0) AND (loContentEncoding.ContentsEqual("identity",0) <> 1)) THEN
? "Unexpected content encoding; do not use this response as the file."
RELEASE loToken
RELEASE loHttp
RELEASE loResp
RELEASE loResult
RELEASE loEndpoint
RELEASE loFac
RELEASE loUuid
RELEASE loTarget
RELEASE loStreamRequest
RELEASE loServiceUrl
RELEASE loDownloadHttp
RELEASE loServiceHost
RELEASE loServiceQuery
RELEASE loAuthMatch
RELEASE loTokenFiles
RELEASE loSharepointToken
RELEASE loContentEncoding
CANCEL
ENDIF
loDeclaredLength = CreateObject('Chilkat.StringBuilder')
loDeclaredLength.Append(loResp.GetHeaderField("Content-Length"))
loDeclaredLength.Trim()
IF (loDeclaredLength.Length > 0) THEN
loLengthMatch = CreateObject('Chilkat.JsonObject')
lnLengthMatched = loDeclaredLength.RegexMatch("\A[0-9]+\z",loLengthMatch,100)
IF (lnLengthMatched <> 1) THEN
? "Invalid Content-Length; do not use this response as the file."
RELEASE loToken
RELEASE loHttp
RELEASE loResp
RELEASE loResult
RELEASE loEndpoint
RELEASE loFac
RELEASE loUuid
RELEASE loTarget
RELEASE loStreamRequest
RELEASE loServiceUrl
RELEASE loDownloadHttp
RELEASE loServiceHost
RELEASE loServiceQuery
RELEASE loAuthMatch
RELEASE loTokenFiles
RELEASE loSharepointToken
RELEASE loContentEncoding
RELEASE loDeclaredLength
RELEASE loLengthMatch
CANCEL
ENDIF
* Compare decimal strings rather than narrowing a large file length to int.
DO WHILE ((loDeclaredLength.Length > 1) AND (loDeclaredLength.StartsWith("0",1) = 1))
loDeclaredLength.RemoveCharsAt(0,1)
ENDDO
IF (loDeclaredLength.ContentsEqual(lcActualSize,1) <> 1) THEN
? "Content transfer did not complete: byte count differs from Content-Length."
RELEASE loToken
RELEASE loHttp
RELEASE loResp
RELEASE loResult
RELEASE loEndpoint
RELEASE loFac
RELEASE loUuid
RELEASE loTarget
RELEASE loStreamRequest
RELEASE loServiceUrl
RELEASE loDownloadHttp
RELEASE loServiceHost
RELEASE loServiceQuery
RELEASE loAuthMatch
RELEASE loTokenFiles
RELEASE loSharepointToken
RELEASE loContentEncoding
RELEASE loDeclaredLength
RELEASE loLengthMatch
CANCEL
ENDIF
ENDIF
lnSuccess = loFac.FileRename(lcPartialPath,lcFinalPath)
IF (lnSuccess <> 1) THEN
? "Download completed but final rename failed; retain the .part file."
RELEASE loToken
RELEASE loHttp
RELEASE loResp
RELEASE loResult
RELEASE loEndpoint
RELEASE loFac
RELEASE loUuid
RELEASE loTarget
RELEASE loStreamRequest
RELEASE loServiceUrl
RELEASE loDownloadHttp
RELEASE loServiceHost
RELEASE loServiceQuery
RELEASE loAuthMatch
RELEASE loTokenFiles
RELEASE loSharepointToken
RELEASE loContentEncoding
RELEASE loDeclaredLength
RELEASE loLengthMatch
CANCEL
ENDIF
? "Saved file: " + lcFinalPath
RELEASE loToken
RELEASE loHttp
RELEASE loResp
RELEASE loResult
RELEASE loEndpoint
RELEASE loFac
RELEASE loUuid
RELEASE loTarget
RELEASE loStreamRequest
RELEASE loServiceUrl
RELEASE loDownloadHttp
RELEASE loServiceHost
RELEASE loServiceQuery
RELEASE loAuthMatch
RELEASE loTokenFiles
RELEASE loSharepointToken
RELEASE loContentEncoding
RELEASE loDeclaredLength
RELEASE loLengthMatch