Sample code for 30+ languages & platforms
AutoIt Requires Chilkat v11.7.0+

Box: Upload a Large File in Parts and Commit the Session

See more Box Examples

Run the reusable setup once per HttpCurl object, then select names and execute the operation. The setup is repeated here only to make this published example independently runnable. Resolve documents by name, then perform the explicit chunked-upload session, part, and commit loop. Supports 20 MB through 2 GB using int. Saves recovery information and honors bounded commit Retry-After.

See the Box API guide for setup and the complete workflow.

Chilkat AutoIt Downloads

AutoIt
Local $bSuccess = False

;  Requires Chilkat 11.7.0 or later and a previously unlocked Chilkat bundle.
;  See Global Unlock Sample.
;  Guide: Box API Guide.

$bSuccess = False

;  BEGIN ONE-TIME SETUP
;  This block is repeated so each published example can run on its own.
;  In an application, run the setup example once and pass the SAME curl object
;  to operation code below. Do not recreate it for every operation.
;  See Reusable Box HttpCurl Setup.
$oCurl = ObjCreate("Chilkat.HttpCurl")
$oCurl.SetVar "access_token","BOX_ACCESS_TOKEN"
$oCurl.SetVar "parent_name","/"
;  Box's fixed root ID is an implementation detail; callers supply names.
$oCurl.SetVar "parent_id","0"
$oSetupCommand = ObjCreate("Chilkat.StringBuilder")
Local $iSetupReplacements

;  Register findParent; registration sends no request.
$oSetupCommand.SetString("curl -X GET ""https://api.box.com/2.0/folders/0/items?limit=1000&fields=id,type,name"" -H ""Authorization: Bearer ACCESS_TOKEN""")
$iSetupReplacements = $oSetupCommand.Replace("ACCESS_TOKEN",$oCurl.GetVar("access_token"))
$bSuccess = $oCurl.AddFunction("findParent",$oSetupCommand.GetAsString())
If ($bSuccess <> True) Then
    ConsoleWrite($oCurl.LastErrorText & @CRLF)
    Exit
EndIf

;  Register findFolder; registration sends no request.
$oSetupCommand.SetString("curl -X GET ""https://api.box.com/2.0/folders/{{parent_id}}/items?limit=1000&fields=id,type,name"" -H ""Authorization: Bearer ACCESS_TOKEN""")
$iSetupReplacements = $oSetupCommand.Replace("ACCESS_TOKEN",$oCurl.GetVar("access_token"))
$bSuccess = $oCurl.AddFunction("findFolder",$oSetupCommand.GetAsString())
If ($bSuccess <> True) Then
    ConsoleWrite($oCurl.LastErrorText & @CRLF)
    Exit
EndIf

;  Register findFile; registration sends no request.
$oSetupCommand.SetString("curl -X GET ""https://api.box.com/2.0/folders/{{folder_id}}/items?limit=1000&fields=id,type,name"" -H ""Authorization: Bearer ACCESS_TOKEN""")
$iSetupReplacements = $oSetupCommand.Replace("ACCESS_TOKEN",$oCurl.GetVar("access_token"))
$bSuccess = $oCurl.AddFunction("findFile",$oSetupCommand.GetAsString())
If ($bSuccess <> True) Then
    ConsoleWrite($oCurl.LastErrorText & @CRLF)
    Exit
EndIf

;  Register findDestination; registration sends no request.
$oSetupCommand.SetString("curl -X GET ""https://api.box.com/2.0/folders/0/items?limit=1000&fields=id,type,name"" -H ""Authorization: Bearer ACCESS_TOKEN""")
$iSetupReplacements = $oSetupCommand.Replace("ACCESS_TOKEN",$oCurl.GetVar("access_token"))
$bSuccess = $oCurl.AddFunction("findDestination",$oSetupCommand.GetAsString())
If ($bSuccess <> True) Then
    ConsoleWrite($oCurl.LastErrorText & @CRLF)
    Exit
EndIf

;  Register getFileDetails; registration sends no request.
$oSetupCommand.SetString("curl -X GET ""https://api.box.com/2.0/files/{{file_id}}?fields=id,sha1,file_version"" -H ""Authorization: Bearer ACCESS_TOKEN""")
$iSetupReplacements = $oSetupCommand.Replace("ACCESS_TOKEN",$oCurl.GetVar("access_token"))
$bSuccess = $oCurl.AddFunction("getFileDetails",$oSetupCommand.GetAsString())
If ($bSuccess <> True) Then
    ConsoleWrite($oCurl.LastErrorText & @CRLF)
    Exit
EndIf

;  Register getEnterprise; registration sends no request.
$oSetupCommand.SetString("curl -X GET ""https://api.box.com/2.0/users/me?fields=enterprise"" -H ""Authorization: Bearer ACCESS_TOKEN""")
$iSetupReplacements = $oSetupCommand.Replace("ACCESS_TOKEN",$oCurl.GetVar("access_token"))
$bSuccess = $oCurl.AddFunction("getEnterprise",$oSetupCommand.GetAsString())
If ($bSuccess <> True) Then
    ConsoleWrite($oCurl.LastErrorText & @CRLF)
    Exit
EndIf

;  Register output rules once. Chilkat 11.7.0 evaluates {{name}} variables
;  when extracting each output, using the current value at that time.
$bSuccess = $oCurl.AddOutput2("findParent","entries","name","{{parent_name}}",True,"id","parent_id")
If ($bSuccess <> True) Then
    ConsoleWrite($oCurl.LastErrorText & @CRLF)
    Exit
EndIf

$bSuccess = $oCurl.AddOutput2("findFolder","entries","name","{{folder_name}}",True,"id","folder_id")
If ($bSuccess <> True) Then
    ConsoleWrite($oCurl.LastErrorText & @CRLF)
    Exit
EndIf

$bSuccess = $oCurl.AddOutput2("findFile","entries","name","{{file_name}}",True,"id","file_id")
If ($bSuccess <> True) Then
    ConsoleWrite($oCurl.LastErrorText & @CRLF)
    Exit
EndIf

$bSuccess = $oCurl.AddOutput2("findDestination","entries","name","{{destination_name}}",True,"id","destination_id")
If ($bSuccess <> True) Then
    ConsoleWrite($oCurl.LastErrorText & @CRLF)
    Exit
EndIf

$bSuccess = $oCurl.AddOutput("getFileDetails","file_version.id","file_version_id")
If ($bSuccess <> True) Then
    ConsoleWrite($oCurl.LastErrorText & @CRLF)
    Exit
EndIf

$bSuccess = $oCurl.AddOutput("getFileDetails","sha1","file_sha1")
If ($bSuccess <> True) Then
    ConsoleWrite($oCurl.LastErrorText & @CRLF)
    Exit
EndIf

$bSuccess = $oCurl.AddOutput("getEnterprise","enterprise.id","enterprise_id")
If ($bSuccess <> True) Then
    ConsoleWrite($oCurl.LastErrorText & @CRLF)
    Exit
EndIf

;  END ONE-TIME SETUP
;  The name lookups below assume each listing fits in one page (1000 items).
;  Parent and destination names select root children; folder_name selects a child
;  of parent_name. "/" selects the root parent. These are not arbitrary paths.

;  BEGIN OPERATION -- keep the configured object when reusing it.
;  Inputs are names. Retain cached IDs when the selected names have not changed.
Local $sParentName = "/"
Local $sFolderName = "documents"
If (($oCurl.GetVar("parent_name") <> $sParentName) Or (($sParentName = "/") And ($oCurl.VarDefined("parent_id") = False))) Then
    $oCurl.SetVar "parent_name",$sParentName
    $oCurl.ClearVar "parent_id"
    $oCurl.ClearVar "folder_id"
    $oCurl.ClearVar "file_id"
    $oCurl.ClearVar "file_version_id"
    $oCurl.ClearVar "file_sha1"
    If ($sParentName = "/") Then
        $oCurl.SetVar "parent_id","0"
    EndIf

EndIf

If ($oCurl.GetVar("folder_name") <> $sFolderName) Then
    $oCurl.SetVar "folder_name",$sFolderName
    $oCurl.ClearVar "folder_id"
    $oCurl.ClearVar "file_id"
    $oCurl.ClearVar "file_version_id"
    $oCurl.ClearVar "file_sha1"
EndIf

;  Resolve the named destination first. HttpCurl does not expand variables
;  inside multipart -F attributes in the tested build, so this upload is two phases.
$oCurl.ClearTargetOutput "*"
$oAuthorizedCommand1 = ObjCreate("Chilkat.StringBuilder")
$oAuthorizedCommand1.SetString("curl -X GET ""https://api.box.com/2.0/folders/{{folder_id}}?fields=id"" -H ""Authorization: Bearer {{access_token}}""")
Local $iHeaderReplacement1 = $oAuthorizedCommand1.Replace("{{access_token}}",$oCurl.GetVar("access_token"))
$bSuccess = $oCurl.DoYourThing($oAuthorizedCommand1.GetAsString())
If (($bSuccess <> True) Or ($oCurl.StatusCode <> 200)) Then
    ConsoleWrite("Box request failed. HTTP status: " & $oCurl.StatusCode & @CRLF)
    ConsoleWrite("Failure reason: " & $oCurl.FailReason & @CRLF)
    ConsoleWrite($oCurl.ResponseBodyStr & @CRLF)
    Exit
EndIf

;  This example limits size to 2 GB so offsets fit all generated languages' integers.
;  The source must not change during hashing or upload. Create qa_output first.
Local $sLocalPath = "qa_data/large-document.zip"
$oFile = ObjCreate("Chilkat.FileAccess")
;  Check the decimal size before converting so an oversized file cannot overflow int.
Local $sizeString = $oFile.FileSizeStr($sLocalPath)
If ($oFile.LastMethodSuccess <> True) Then
    ConsoleWrite($oFile.LastErrorText & @CRLF)
    Exit
EndIf

$oSizeText = ObjCreate("Chilkat.StringBuilder")
$oSizeText.SetString($sizeString)
$oSizeMatch = ObjCreate("Chilkat.JsonObject")
If ($oSizeText.RegexMatch("^([0-9]{1,9}|1[0-9]{9}|2000000000)$",$oSizeMatch,100) <> 1) Then
    ConsoleWrite("Choose an input between 20 MB and 2 GB for this example." & @CRLF)
    Exit
EndIf

Local $iFileSize = Int($sizeString)
If ($iFileSize < 20971520) Then
    ConsoleWrite("Choose an input between 20 MB and 2 GB for this example." & @CRLF)
    Exit
EndIf

$oHttp = ObjCreate("Chilkat.Http")
$oHttp.AuthToken = $oCurl.GetVar("access_token")
$oResponse = ObjCreate("Chilkat.HttpResponse")
$oRequest = ObjCreate("Chilkat.JsonObject")
$oRequest.UpdateString("folder_id",$oCurl.GetVar("folder_id"))
$oRequest.UpdateString("file_name","large-document.zip")
$oRequest.UpdateInt("file_size",$iFileSize)
$bSuccess = $oHttp.HttpJson("POST","https://upload.box.com/api/2.0/files/upload_sessions",$oRequest,"application/json",$oResponse)
If ($bSuccess <> True) Then
    ConsoleWrite($oHttp.LastErrorText & @CRLF)
    Exit
EndIf

If ($oResponse.StatusCode <> 201) Then
    ConsoleWrite($oResponse.BodyStr & @CRLF)
    Exit
EndIf

$oSession = ObjCreate("Chilkat.JsonObject")
$bSuccess = $oSession.Load($oResponse.BodyStr)
If ($bSuccess <> True) Then
    ConsoleWrite($oSession.LastErrorText & @CRLF)
    Exit
EndIf

$bSuccess = $oSession.WriteFile("qa_output/box_upload_session.json")
If ($bSuccess <> True) Then
    ConsoleWrite($oSession.LastErrorText & @CRLF)
    Exit
EndIf

Local $iPartSize = $oSession.IntOf("part_size")
Local $sUploadUrl = $oSession.StringOf("session_endpoints.upload_part")
Local $sCommitUrl = $oSession.StringOf("session_endpoints.commit")
If (($iPartSize <= 0) Or ($sUploadUrl = "") Or ($sCommitUrl = "")) Then
    ConsoleWrite("Invalid session response." & @CRLF)
    Exit
EndIf

$oHash = ObjCreate("Chilkat.Crypt2")
$oHash.HashAlgorithm = "sha1"
$oHash.EncodingMode = "base64"
Local $sFileDigest = $oHash.HashFileENC($sLocalPath)
If ($oHash.LastMethodSuccess <> True) Then
    ConsoleWrite($oHash.LastErrorText & @CRLF)
    Exit
EndIf

$bSuccess = $oFile.FileOpen($sLocalPath,2147483648,1,3,0)
If ($bSuccess <> True) Then
    ConsoleWrite($oFile.LastErrorText & @CRLF)
    Exit
EndIf

$oCommit = ObjCreate("Chilkat.JsonObject")
$oPartResponse = ObjCreate("Chilkat.JsonObject")
$oChunk = ObjCreate("Chilkat.BinData")
$oRange = ObjCreate("Chilkat.StringBuilder")
$oDigestHeader = ObjCreate("Chilkat.StringBuilder")
Local $iOffset = 0
Local $iPartIndex = 0
Local $iPartLength
Local $iLastByte
Local $sPartDigest
While $iOffset < $iFileSize
    $oChunk.Clear()
    $bSuccess = $oFile.FileReadBd($iPartSize,$oChunk)
    If ($bSuccess <> True) Then
        ConsoleWrite($oFile.LastErrorText & @CRLF)
        $oFile.FileClose 
        Exit
    EndIf

    $iPartLength = $oChunk.NumBytes
    If ($iPartLength <= 0) Then
        ConsoleWrite("Unexpected end of file." & @CRLF)
        $oFile.FileClose 
        Exit
    EndIf

    $iLastByte = $iOffset + ($iPartLength - 1)
    $oRange.Clear 
    $oRange.Append("bytes ")
    $oRange.AppendInt($iOffset)
    $oRange.Append("-")
    $oRange.AppendInt($iLastByte)
    $oRange.Append("/")
    $oRange.AppendInt($iFileSize)
    $sPartDigest = $oHash.HashBdENC($oChunk)
    If ($oHash.LastMethodSuccess <> True) Then
        ConsoleWrite($oHash.LastErrorText & @CRLF)
        $oFile.FileClose 
        Exit
    EndIf

    $oDigestHeader.SetString("sha=")
    $oDigestHeader.Append($sPartDigest)
    $oHttp.SetRequestHeader "Digest",$oDigestHeader.GetAsString()
    $oHttp.SetRequestHeader "Content-Range",$oRange.GetAsString()
    $bSuccess = $oHttp.HttpBd("PUT",$sUploadUrl,$oChunk,"application/octet-stream",$oResponse)
    If (($bSuccess <> True) Or ($oResponse.StatusCode <> 200)) Then
        ConsoleWrite("Part failed. HTTP status: " & $oResponse.StatusCode & @CRLF)
        ConsoleWrite($oResponse.BodyStr & @CRLF)
        ConsoleWrite("Inspect the saved session and server list_parts before retrying this part." & @CRLF)
        $oFile.FileClose 
        Exit
    EndIf

    $bSuccess = $oPartResponse.Load($oResponse.BodyStr)
    If ($bSuccess <> True) Then
        $oFile.FileClose 
        Exit
    EndIf

    $oCommit.I = $iPartIndex
    ;  Copy the server's acknowledged part fields into the commit manifest.
    $oCommit.UpdateString("parts[i].part_id",$oPartResponse.StringOf("part.part_id"))
    $oCommit.UpdateInt("parts[i].offset",$oPartResponse.IntOf("part.offset"))
    $oCommit.UpdateInt("parts[i].size",$oPartResponse.IntOf("part.size"))
    $oCommit.UpdateString("parts[i].sha1",$oPartResponse.StringOf("part.sha1"))
    $bSuccess = $oCommit.WriteFile("qa_output/box_upload_parts.json")
    If ($bSuccess <> True) Then
        ConsoleWrite($oCommit.LastErrorText & @CRLF)
        $oFile.FileClose 
        Exit
    EndIf

    $iOffset = $iOffset + $iPartLength
    $iPartIndex = $iPartIndex + 1
Wend
$oFile.FileClose 
$oHttp.RemoveRequestHeader "Content-Range"
$oDigestHeader.SetString("sha=")
$oDigestHeader.Append($sFileDigest)
$oHttp.SetRequestHeader "Digest",$oDigestHeader.GetAsString()
Local $iAttempts = 0
Local $iWaitSeconds
$oRetryHeader = ObjCreate("Chilkat.StringBuilder")
$oRetryMatch = ObjCreate("Chilkat.JsonObject")
Local $bCompleted = False
While ($iAttempts < 10) And ($bCompleted = False)
    $bSuccess = $oHttp.HttpJson("POST",$sCommitUrl,$oCommit,"application/json",$oResponse)
    If ($bSuccess <> True) Then
        ConsoleWrite("Commit failed: " & $oResponse.StatusCode & @CRLF)
        ConsoleWrite($oResponse.BodyStr & @CRLF)
        Exit
    EndIf

    If ($oResponse.StatusCode = 201) Then
        $bCompleted = True
    Else
        If ($oResponse.StatusCode <> 202) Then
            ConsoleWrite("Unexpected commit status: " & $oResponse.StatusCode & @CRLF)
            Exit
        EndIf

        ;  Box's asynchronous commit response supplies Retry-After in seconds.
        $oRetryHeader.SetString($oResponse.GetHeaderField("Retry-After"))
        If ($oRetryHeader.RegexMatch("^[0-9]{1,2}$",$oRetryMatch,100) <> 1) Then
            ConsoleWrite("Commit pending. Preserve the session and inspect Retry-After before resuming: " & $oRetryHeader.GetAsString() & @CRLF)
            Exit
        EndIf

        $iWaitSeconds = Int($oRetryHeader.GetAsString())
        If (($iWaitSeconds < 1) Or ($iWaitSeconds > 60)) Then
            ConsoleWrite("Commit pending. Resume commit after Retry-After: " & $oResponse.GetHeaderField("Retry-After") & @CRLF)
            Exit
        EndIf

        $oHttp.SleepMs $iWaitSeconds * 1000
    EndIf

    $iAttempts = $iAttempts + 1
Wend
If ($bCompleted = False) Then
    ConsoleWrite("Commit still pending; retain session and part manifests to resume commit later." & @CRLF)
    Exit
EndIf

ConsoleWrite("Upload committed: " & $oResponse.BodyStr & @CRLF)