Swift Requires Chilkat v11.7.0+
Swift
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 Swift Downloads
func chilkatTest() {
var success: Bool = false
// Requires Chilkat 11.7.0 or later and a previously unlocked Chilkat bundle.
// See Global Unlock Sample.
// Guide: Box API Guide.
success = 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.
let curl = CkoHttpCurl()!
curl.setVar(varName: "access_token", varValue: "BOX_ACCESS_TOKEN")
curl.setVar(varName: "parent_name", varValue: "/")
// Box's fixed root ID is an implementation detail; callers supply names.
curl.setVar(varName: "parent_id", varValue: "0")
let setupCommand = CkoStringBuilder()!
var setupReplacements: Int
// Register findParent; registration sends no request.
setupCommand.setString(value: "curl -X GET \"https://api.box.com/2.0/folders/0/items?limit=1000&fields=id,type,name\" -H \"Authorization: Bearer ACCESS_TOKEN\"")
setupReplacements = setupCommand.replace(value: "ACCESS_TOKEN", replacement: curl.getVar(varName: "access_token")).intValue
success = curl.addFunction(funcName: "findParent", curl: setupCommand.getAsString())
if success != true {
print("\(curl.lastErrorText!)")
return
}
// Register findFolder; registration sends no request.
setupCommand.setString(value: "curl -X GET \"https://api.box.com/2.0/folders/{{parent_id}}/items?limit=1000&fields=id,type,name\" -H \"Authorization: Bearer ACCESS_TOKEN\"")
setupReplacements = setupCommand.replace(value: "ACCESS_TOKEN", replacement: curl.getVar(varName: "access_token")).intValue
success = curl.addFunction(funcName: "findFolder", curl: setupCommand.getAsString())
if success != true {
print("\(curl.lastErrorText!)")
return
}
// Register findFile; registration sends no request.
setupCommand.setString(value: "curl -X GET \"https://api.box.com/2.0/folders/{{folder_id}}/items?limit=1000&fields=id,type,name\" -H \"Authorization: Bearer ACCESS_TOKEN\"")
setupReplacements = setupCommand.replace(value: "ACCESS_TOKEN", replacement: curl.getVar(varName: "access_token")).intValue
success = curl.addFunction(funcName: "findFile", curl: setupCommand.getAsString())
if success != true {
print("\(curl.lastErrorText!)")
return
}
// Register findDestination; registration sends no request.
setupCommand.setString(value: "curl -X GET \"https://api.box.com/2.0/folders/0/items?limit=1000&fields=id,type,name\" -H \"Authorization: Bearer ACCESS_TOKEN\"")
setupReplacements = setupCommand.replace(value: "ACCESS_TOKEN", replacement: curl.getVar(varName: "access_token")).intValue
success = curl.addFunction(funcName: "findDestination", curl: setupCommand.getAsString())
if success != true {
print("\(curl.lastErrorText!)")
return
}
// Register getFileDetails; registration sends no request.
setupCommand.setString(value: "curl -X GET \"https://api.box.com/2.0/files/{{file_id}}?fields=id,sha1,file_version\" -H \"Authorization: Bearer ACCESS_TOKEN\"")
setupReplacements = setupCommand.replace(value: "ACCESS_TOKEN", replacement: curl.getVar(varName: "access_token")).intValue
success = curl.addFunction(funcName: "getFileDetails", curl: setupCommand.getAsString())
if success != true {
print("\(curl.lastErrorText!)")
return
}
// Register getEnterprise; registration sends no request.
setupCommand.setString(value: "curl -X GET \"https://api.box.com/2.0/users/me?fields=enterprise\" -H \"Authorization: Bearer ACCESS_TOKEN\"")
setupReplacements = setupCommand.replace(value: "ACCESS_TOKEN", replacement: curl.getVar(varName: "access_token")).intValue
success = curl.addFunction(funcName: "getEnterprise", curl: setupCommand.getAsString())
if success != true {
print("\(curl.lastErrorText!)")
return
}
// Register output rules once. Chilkat 11.7.0 evaluates {{name}} variables
// when extracting each output, using the current value at that time.
success = curl.addOutput2(funcName: "findParent", arrayPath: "entries", wherePath: "name", whereValue: "{{parent_name}}", caseSensitive: true, subPath: "id", varName: "parent_id")
if success != true {
print("\(curl.lastErrorText!)")
return
}
success = curl.addOutput2(funcName: "findFolder", arrayPath: "entries", wherePath: "name", whereValue: "{{folder_name}}", caseSensitive: true, subPath: "id", varName: "folder_id")
if success != true {
print("\(curl.lastErrorText!)")
return
}
success = curl.addOutput2(funcName: "findFile", arrayPath: "entries", wherePath: "name", whereValue: "{{file_name}}", caseSensitive: true, subPath: "id", varName: "file_id")
if success != true {
print("\(curl.lastErrorText!)")
return
}
success = curl.addOutput2(funcName: "findDestination", arrayPath: "entries", wherePath: "name", whereValue: "{{destination_name}}", caseSensitive: true, subPath: "id", varName: "destination_id")
if success != true {
print("\(curl.lastErrorText!)")
return
}
success = curl.addOutput(funcName: "getFileDetails", jsonPath: "file_version.id", varName: "file_version_id")
if success != true {
print("\(curl.lastErrorText!)")
return
}
success = curl.addOutput(funcName: "getFileDetails", jsonPath: "sha1", varName: "file_sha1")
if success != true {
print("\(curl.lastErrorText!)")
return
}
success = curl.addOutput(funcName: "getEnterprise", jsonPath: "enterprise.id", varName: "enterprise_id")
if success != true {
print("\(curl.lastErrorText!)")
return
}
// 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.
var parentName: String? = "/"
var folderName: String? = "documents"
if (curl.getVar(varName: "parent_name") != parentName) || ((parentName == "/") && (curl.varDefined(varName: "parent_id") == false)) {
curl.setVar(varName: "parent_name", varValue: parentName)
curl.clearVar(varName: "parent_id")
curl.clearVar(varName: "folder_id")
curl.clearVar(varName: "file_id")
curl.clearVar(varName: "file_version_id")
curl.clearVar(varName: "file_sha1")
if parentName == "/" {
curl.setVar(varName: "parent_id", varValue: "0")
}
}
if curl.getVar(varName: "folder_name") != folderName {
curl.setVar(varName: "folder_name", varValue: folderName)
curl.clearVar(varName: "folder_id")
curl.clearVar(varName: "file_id")
curl.clearVar(varName: "file_version_id")
curl.clearVar(varName: "file_sha1")
}
// Resolve the named destination first. HttpCurl does not expand variables
// inside multipart -F attributes in the tested build, so this upload is two phases.
curl.clearTargetOutput(varName: "*")
let authorizedCommand1 = CkoStringBuilder()!
authorizedCommand1.setString(value: "curl -X GET \"https://api.box.com/2.0/folders/{{folder_id}}?fields=id\" -H \"Authorization: Bearer {{access_token}}\"")
var headerReplacement1: Int = authorizedCommand1.replace(value: "{{access_token}}", replacement: curl.getVar(varName: "access_token")).intValue
success = curl.doYourThing(targetCurl: authorizedCommand1.getAsString())
if (success != true) || (curl.statusCode.intValue != 200) {
print("Box request failed. HTTP status: \(curl.statusCode.intValue)")
print("Failure reason: \(curl.failReason.intValue)")
print("\(curl.responseBodyStr!)")
return
}
// 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.
var localPath: String? = "qa_data/large-document.zip"
let file = CkoFileAccess()!
// Check the decimal size before converting so an oversized file cannot overflow int.
var sizeString: String? = file.fileSizeStr(filePath: localPath)
if file.lastMethodSuccess != true {
print("\(file.lastErrorText!)")
return
}
let sizeText = CkoStringBuilder()!
sizeText.setString(value: sizeString)
let sizeMatch = CkoJsonObject()!
if sizeText.regexMatch(pattern: "^([0-9]{1,9}|1[0-9]{9}|2000000000)$", json: sizeMatch, timeoutMs: 100).intValue != 1 {
print("Choose an input between 20 MB and 2 GB for this example.")
return
}
var fileSize: Int = [sizeString intValue]
if fileSize < 20971520 {
print("Choose an input between 20 MB and 2 GB for this example.")
return
}
let http = CkoHttp()!
http.authToken = curl.getVar(varName: "access_token")
let response = CkoHttpResponse()!
let request = CkoJsonObject()!
request.updateString(jsonPath: "folder_id", value: curl.getVar(varName: "folder_id"))
request.updateString(jsonPath: "file_name", value: "large-document.zip")
request.updateInt(jsonPath: "file_size", value: fileSize)
success = http.httpJson(verb: "POST", url: "https://upload.box.com/api/2.0/files/upload_sessions", json: request, contentType: "application/json", response: response)
if success != true {
print("\(http.lastErrorText!)")
return
}
if response.statusCode.intValue != 201 {
print("\(response.bodyStr!)")
return
}
let session = CkoJsonObject()!
success = session.load(json: response.bodyStr)
if success != true {
print("\(session.lastErrorText!)")
return
}
success = session.writeFile(path: "qa_output/box_upload_session.json")
if success != true {
print("\(session.lastErrorText!)")
return
}
var partSize: Int = session.int(of: "part_size").intValue
var uploadUrl: String? = session.string(of: "session_endpoints.upload_part")
var commitUrl: String? = session.string(of: "session_endpoints.commit")
if (partSize <= 0) || (uploadUrl == "") || (commitUrl == "") {
print("Invalid session response.")
return
}
let hash = CkoCrypt2()!
hash.hashAlgorithm = "sha1"
hash.encodingMode = "base64"
var fileDigest: String? = hash.hashFileENC(path: localPath)
if hash.lastMethodSuccess != true {
print("\(hash.lastErrorText!)")
return
}
success = file.fileOpen(path: localPath, accessMode: 2147483648, shareMode: 1, createDisp: 3, attr: 0)
if success != true {
print("\(file.lastErrorText!)")
return
}
let commit = CkoJsonObject()!
let partResponse = CkoJsonObject()!
let chunk = CkoBinData()!
let range = CkoStringBuilder()!
let digestHeader = CkoStringBuilder()!
var offset: Int = 0
var partIndex: Int = 0
var partLength: Int
var lastByte: Int
var partDigest: String?
while offset < fileSize {
chunk.clear()
success = file.fileReadBd(maxNumBytes: partSize, binData: chunk)
if success != true {
print("\(file.lastErrorText!)")
file.fileClose()
return
}
partLength = chunk.numBytes.intValue
if partLength <= 0 {
print("Unexpected end of file.")
file.fileClose()
return
}
lastByte = offset + (partLength - 1)
range.clear()
range.append(value: "bytes ")
range.appendInt(value: offset)
range.append(value: "-")
range.appendInt(value: lastByte)
range.append(value: "/")
range.appendInt(value: fileSize)
partDigest = hash.hashBdENC(bd: chunk)
if hash.lastMethodSuccess != true {
print("\(hash.lastErrorText!)")
file.fileClose()
return
}
digestHeader.setString(value: "sha=")
digestHeader.append(value: partDigest)
http.setRequestHeader(name: "Digest", value: digestHeader.getAsString())
http.setRequestHeader(name: "Content-Range", value: range.getAsString())
success = http.httpBd(verb: "PUT", url: uploadUrl, bd: chunk, contentType: "application/octet-stream", response: response)
if (success != true) || (response.statusCode.intValue != 200) {
print("Part failed. HTTP status: \(response.statusCode.intValue)")
print("\(response.bodyStr!)")
print("Inspect the saved session and server list_parts before retrying this part.")
file.fileClose()
return
}
success = partResponse.load(json: response.bodyStr)
if success != true {
file.fileClose()
return
}
commit.i = partIndex
// Copy the server's acknowledged part fields into the commit manifest.
commit.updateString(jsonPath: "parts[i].part_id", value: partResponse.string(of: "part.part_id"))
commit.updateInt(jsonPath: "parts[i].offset", value: partResponse.int(of: "part.offset").intValue)
commit.updateInt(jsonPath: "parts[i].size", value: partResponse.int(of: "part.size").intValue)
commit.updateString(jsonPath: "parts[i].sha1", value: partResponse.string(of: "part.sha1"))
success = commit.writeFile(path: "qa_output/box_upload_parts.json")
if success != true {
print("\(commit.lastErrorText!)")
file.fileClose()
return
}
offset = offset + partLength
partIndex = partIndex + 1
}
file.fileClose()
http.removeRequestHeader(name: "Content-Range")
digestHeader.setString(value: "sha=")
digestHeader.append(value: fileDigest)
http.setRequestHeader(name: "Digest", value: digestHeader.getAsString())
var attempts: Int = 0
var waitSeconds: Int
let retryHeader = CkoStringBuilder()!
let retryMatch = CkoJsonObject()!
var completed: Bool = false
while (attempts < 10) && (completed == false) {
success = http.httpJson(verb: "POST", url: commitUrl, json: commit, contentType: "application/json", response: response)
if success != true {
print("Commit failed: \(response.statusCode.intValue)")
print("\(response.bodyStr!)")
return
}
if response.statusCode.intValue == 201 {
completed = true
}
else {
if response.statusCode.intValue != 202 {
print("Unexpected commit status: \(response.statusCode.intValue)")
return
}
// Box's asynchronous commit response supplies Retry-After in seconds.
retryHeader.setString(value: response.getHeaderField(fieldName: "Retry-After"))
if retryHeader.regexMatch(pattern: "^[0-9]{1,2}$", json: retryMatch, timeoutMs: 100).intValue != 1 {
print("Commit pending. Preserve the session and inspect Retry-After before resuming: \(retryHeader.getAsString()!)")
return
}
waitSeconds = [retryHeader.getAsString() intValue]
if (waitSeconds < 1) || (waitSeconds > 60) {
print("Commit pending. Resume commit after Retry-After: \(response.getHeaderField(fieldName: "Retry-After")!)")
return
}
http.sleepMs(millisec: waitSeconds * 1000)
}
attempts = attempts + 1
}
if completed == false {
print("Commit still pending; retain session and part manifests to resume commit later.")
return
}
print("Upload committed: \(response.bodyStr!)")
}