DataFlex
DataFlex
OneDrive -- Upload Large Files with an Upload Session
See more OneDrive Examples
Demonstrates how to upload large files with an upload session. See OneDrive Upload Session for more general information.Chilkat DataFlex Downloads
Use ChilkatAx-win32.pkg
Procedure Test
Boolean iSuccess
Handle hoJson
Handle hoHttp
String sUrl
Variant vResp
Handle hoResp
Handle hoJsonSession
Integer iFragSize
String sLocalFilePath
Handle hoFac
Integer iFileSize
Integer iNumFragments
Integer i
Handle hoUploadUrl
Variant vReq
Handle hoReq
Handle hoSbOffset
Handle hoSbNumBytes
Handle hoSbRange
Integer iBytesRemaining
Integer iChunkSize
Integer iExpectedStatusCode
Integer iNumReplaced
String sDomain
String sTemp1
String sTemp2
Integer iTemp1
Move False To iSuccess
// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
// This example uses the OAuth client credentials flow.
// See How to Create an Azure App Registration for OAuth 2.0 Client Credentials
// Use your client ID, client secret, and tenant ID in the following lines
Get Create (RefClass(cComChilkatJsonObject)) To hoJson
If (Not(IsComObjectCreated(hoJson))) Begin
Send CreateComObject of hoJson
End
Get ComUpdateString Of hoJson "client_id" "2871da2c-8176-4b7f-869b-2311aa82e743" To iSuccess
Get ComUpdateString Of hoJson "client_secret" "2hu9Q~r5QuryUcEkNbg1btLtnfU1VUXzhSCG6brH" To iSuccess
Get ComUpdateString Of hoJson "scope" "https://graph.microsoft.com/.default" To iSuccess
Get ComUpdateString Of hoJson "token_endpoint" "https://login.microsoftonline.com/114d7ed6-71bf-4dbe-a866-748364121bf2/oauth2/v2.0/token" To iSuccess
Get Create (RefClass(cComChilkatHttp)) To hoHttp
If (Not(IsComObjectCreated(hoHttp))) Begin
Send CreateComObject of hoHttp
End
Get ComEmit Of hoJson To sTemp1
Set ComAuthToken Of hoHttp To sTemp1
// ----------------------------------------------------------------------------
// Step 1: Create an upload session
// To begin a large file upload, your app must first request a new upload session. This creates a
// temporary storage location where the bytes of the file will be saved until the complete file is uploaded.
// Once the last byte of the file has been uploaded the upload session is completed and the final file is shown
// in the destination folder.
// Send the following POST to create an upload session:
// If not using "me", then the path should be /v1.0/users/{id | userPrincipalName}/...
// POST /v1.0/users/{user_id}/drive/root:/{path_to_item}:/createUploadSession
Get ComSetUrlVar Of hoHttp "path_to_item" "/somefolder/big.zip" To iSuccess
Get ComSetUrlVar Of hoHttp "user_id" "4fe732c3-322e-4a6b-b729-2fd1eb5c6104" To iSuccess
Move "https://graph.microsoft.com/v1.0/users/{$user_id}/drive/root:/{$path_to_item}:/createUploadSession" To sUrl
Get Create (RefClass(cComChilkatHttpResponse)) To hoResp
If (Not(IsComObjectCreated(hoResp))) Begin
Send CreateComObject of hoResp
End
Get pvComObject of hoResp to vResp
Get ComHttpStr Of hoHttp "POST" sUrl "{}" "utf-8" "application/json" vResp To iSuccess
If (iSuccess = False) Begin
Get ComLastErrorText Of hoHttp To sTemp1
Showln sTemp1
Procedure_Return
End
// If successful, a 200 status code is returned, with the session details (in JSON format).
Get Create (RefClass(cComChilkatJsonObject)) To hoJsonSession
If (Not(IsComObjectCreated(hoJsonSession))) Begin
Send CreateComObject of hoJsonSession
End
Set ComEmitCompact Of hoJsonSession To False
Get ComBodyStr Of hoResp To sTemp1
Get ComLoad Of hoJsonSession sTemp1 To iSuccess
Get ComStatusCode Of hoResp To iTemp1
If (iTemp1 <> 200) Begin
Get ComEmit Of hoJsonSession To sTemp1
Showln sTemp1
Get ComStatusCode Of hoResp To iTemp1
Showln "Response status = " iTemp1
Procedure_Return
End
Get ComEmit Of hoJsonSession To sTemp1
Showln sTemp1
// A sample response:
// {
// "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#microsoft.graph.uploadSession",
// "uploadUrl": "https://api.onedrive.com/rup/3a33fceb9b74cc15/eyJSZXNvdXJjZUlEI ... 65yDYUiS3JTDnnhqCHxw",
// "expirationDateTime": "2017-06-11T12:40:23.239Z",
// "nextExpectedRanges": [
// "0-"
// ]
// }
//
// ----------------------------------------------------------------------------
// Step 2: Upload Data in Segments (a.k.a. Fragments or Chunks)
// Microsoft states this requirement: Use a fragment size that is a multiple of 320 KiB (320 * 1024 bytes).
// Failing to use a fragment size that is a multiple of 320 KiB can result in large file transfers failing after the
// last fragment is uploaded. (Note: This is a detail imposed by Microsoft's OneDrive server-side implementation.)
Move (320 * 1024) To iFragSize
Move "qa_data/zips/big.zip" To sLocalFilePath
// Upload the file big.zip in 320KiB segments.
// Note: The FileSize method returns a signed 32-bit integer. If the file is potentially larger than 2GB, call FileSizeStr instead to return
// the size of the file as a string, then convert to an integer value.
Get Create (RefClass(cComCkFileAccess)) To hoFac
If (Not(IsComObjectCreated(hoFac))) Begin
Send CreateComObject of hoFac
End
Get ComFileSize Of hoFac sLocalFilePath To iFileSize
// Open the file to get the number of fragments.
Get ComOpenForRead Of hoFac sLocalFilePath To iSuccess
If (iSuccess = False) Begin
Get ComLastErrorText Of hoFac To sTemp1
Showln sTemp1
Procedure_Return
End
Get ComGetNumBlocks Of hoFac iFragSize To iNumFragments
Send ComFileClose To hoFac
Move 0 To i
Showln "fileSize = " iFileSize
Showln "numFragments = " iNumFragments
Get Create (RefClass(cComChilkatUrl)) To hoUploadUrl
If (Not(IsComObjectCreated(hoUploadUrl))) Begin
Send CreateComObject of hoUploadUrl
End
Get ComStringOf Of hoJsonSession "uploadUrl" To sTemp1
Get ComParseUrl Of hoUploadUrl sTemp1 To iSuccess
Set ComEmitCompact Of hoJson To False
Get Create (RefClass(cComChilkatHttpRequest)) To hoReq
If (Not(IsComObjectCreated(hoReq))) Begin
Send CreateComObject of hoReq
End
Set ComHttpVerb Of hoReq To "PUT"
Get ComPathWithQueryParams Of hoUploadUrl To sTemp1
Set ComPath Of hoReq To sTemp1
Set ComContentType Of hoReq To "application/octet-stream"
Get Create (RefClass(cComChilkatStringBuilder)) To hoSbOffset
If (Not(IsComObjectCreated(hoSbOffset))) Begin
Send CreateComObject of hoSbOffset
End
Get Create (RefClass(cComChilkatStringBuilder)) To hoSbNumBytes
If (Not(IsComObjectCreated(hoSbNumBytes))) Begin
Send CreateComObject of hoSbNumBytes
End
Get Create (RefClass(cComChilkatStringBuilder)) To hoSbRange
If (Not(IsComObjectCreated(hoSbRange))) Begin
Send CreateComObject of hoSbRange
End
// IMPORTANT: The uploadUrl is a temporary URL to be used to upload the fragment.
// It requires no authentication (because the URL itself could only have been obtained from an authenticated
// request to start the upload session). Therefore, do not allow the upload URL to be publicly seen,
// otherwise anybody could upload to your OneDrive.
Set ComAuthToken Of hoHttp To ""
Move iFileSize To iBytesRemaining
While (i < iNumFragments)
// The success response code for intermediate chunks is 202,
// whereas the final chunk will have a 201 success response where
// the response body is the JSON DriveItem.
Move iFragSize To iChunkSize
Move 202 To iExpectedStatusCode
If (iBytesRemaining < iChunkSize) Begin
Move iBytesRemaining To iChunkSize
Move 201 To iExpectedStatusCode
End
Showln " this chunkSize = " iChunkSize
// Indicate the fragment in the local file to be streamed in the upload.
Send ComClear To hoSbOffset
Get ComAppendInt Of hoSbOffset (i * iFragSize) To iSuccess
Send ComClear To hoSbNumBytes
Get ComAppendInt Of hoSbNumBytes iChunkSize To iSuccess
Get ComGetAsString Of hoSbOffset To sTemp1
Get ComGetAsString Of hoSbNumBytes To sTemp2
Get ComStreamChunkFromFile Of hoReq sLocalFilePath sTemp1 sTemp2 To iSuccess
// The Content-Range header field must be set for this fragment. For example:
// Content-Range: bytes 0-25/128
Get ComSetString Of hoSbRange "bytes start-end/fileSize" To iSuccess
Get ComReplaceI Of hoSbRange "start" (i * iFragSize) To iNumReplaced
Get ComReplaceI Of hoSbRange "end" (i * iFragSize + iChunkSize - 1) To iNumReplaced
Get ComReplaceI Of hoSbRange "fileSize" iFileSize To iNumReplaced
Get ComGetAsString Of hoSbRange To sTemp1
Send ComAddHeader To hoReq "Content-Range" sTemp1
Get ComGetAsString Of hoSbRange To sTemp1
Showln " this content-range: " sTemp1
Get ComHost Of hoUploadUrl To sDomain
Get pvComObject of hoReq to vReq
Get pvComObject of hoResp to vResp
Get ComHttpSReq Of hoHttp sDomain 443 True vReq vResp To iSuccess
If (iSuccess = False) Begin
Get ComLastErrorText Of hoHttp To sTemp1
Showln sTemp1
Procedure_Return
End
Get ComBodyStr Of hoResp To sTemp1
Get ComLoad Of hoJson sTemp1 To iSuccess
// A 202 response status code indicates success.
Get ComStatusCode Of hoResp To iTemp1
If (iTemp1 <> iExpectedStatusCode) Begin
Get ComEmit Of hoJson To sTemp1
Showln sTemp1
Get ComStatusCode Of hoResp To iTemp1
Showln "Response status = " iTemp1
Procedure_Return
End
Get ComEmit Of hoJson To sTemp1
Showln sTemp1
Showln "---- Chunk " i " uploaded ----"
Move (iBytesRemaining - iChunkSize) To iBytesRemaining
Move (i + 1) To i
Loop
Showln "data uploaded."
// ----------------------------------------------------------------------------
// Sample output for the above session:
// {
// "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#microsoft.graph.uploadSession",
// "uploadUrl": "https://api.onedrive.com/rup/3a33fceb9b74cc15/eyJSZXNvd ... QoKK2iuh1A",
// "expirationDateTime": "2017-06-11T14:04:45.438Z",
// "nextExpectedRanges": [
// "0-"
// ]
// }
//
// fileSize = 1366807
// numFragments = 5
// this chunkSize = 327680
// this content-range: bytes 0-327679/1366807
// {
// "expirationDateTime": "2017-06-11T14:04:45.438Z",
// "nextExpectedRanges": [
// "327680-1366806"
// ]
// }
//
// ---- Chunk 0 uploaded ----
// this chunkSize = 327680
// this content-range: bytes 327680-655359/1366807
// {
// "expirationDateTime": "2017-06-11T14:04:45.438Z",
// "nextExpectedRanges": [
// "655360-1366806"
// ]
// }
//
// ---- Chunk 1 uploaded ----
// this chunkSize = 327680
// this content-range: bytes 655360-983039/1366807
// {
// "expirationDateTime": "2017-06-11T14:04:45.438Z",
// "nextExpectedRanges": [
// "983040-1366806"
// ]
// }
//
// ---- Chunk 2 uploaded ----
// this chunkSize = 327680
// this content-range: bytes 983040-1310719/1366807
// {
// "expirationDateTime": "2017-06-11T14:04:45.438Z",
// "nextExpectedRanges": [
// "1310720-1366806"
// ]
// }
//
// ---- Chunk 3 uploaded ----
// this chunkSize = 56087
// this content-range: bytes 1310720-1366806/1366807
// {
// "createdBy": {
// "application": {
// "displayName": "Chilkat",
// "id": "441c9990"
// },
// "user": {
// "id": "3a33fceb9b74cc15"
// }
// },
// "createdDateTime": "2017-06-04T14:04:47.247Z",
// "cTag": "aYzozQTMzRkNFQjlCNzRDQzE1ITQ4NjguMjU3",
// "eTag": "aM0EzM0ZDRUI5Qjc0Q0MxNSE0ODY4LjA",
// "id": "3A33FCEB9B74CC15!4868",
// "lastModifiedBy": {
// "application": {
// "displayName": "Chilkat",
// "id": "441c9990"
// },
// "user": {
// "id": "3a33fceb9b74cc15"
// }
// },
// "lastModifiedDateTime": "2017-06-04T14:04:47.247Z",
// "name": "big.zip",
// "parentReference": {
// "driveId": "3a33fceb9b74cc15",
// "id": "3A33FCEB9B74CC15!4862",
// "name": "someFolder",
// "path": "/drive/root:/someFolder"
// },
// "size": 1366807,
// "webUrl": "https://1drv.ms/u/s!ABXMdJvr_DM6pgQ",
// "file": {
// "hashes": {
// "sha1Hash": "252059AA13004220DB912B97D4D3FF9599CCD8D9"
// },
// "mimeType": "application/zip"
// },
// "fileSystemInfo": {
// "createdDateTime": "2017-06-04T14:04:47.246Z",
// "lastModifiedDateTime": "2017-06-04T14:04:47.246Z"
// },
// "tags": [
// ],
// "lenses": [
// ]
// }
//
// Response status = 201
End_Procedure