React Native Requires Chilkat v11.7.0+
React Native
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 React Native Downloads
import { BinData, Crypt2, FileAccess, Http, HttpCurl, HttpResponse, JsonObject, StringBuilder } from '@chilkat/react-native'
async function chilkatExample() {
let success = 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.
const curl = new HttpCurl();
curl.setVar('access_token', 'BOX_ACCESS_TOKEN');
curl.setVar('parent_name', '/');
// Box's fixed root ID is an implementation detail; callers supply names.
curl.setVar('parent_id', '0');
const setupCommand = new StringBuilder();
let setupReplacements = 0;
// Register findParent; registration sends no request.
setupCommand.setString('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('ACCESS_TOKEN', curl.getVar('access_token'));
success = true;
try {
curl.addFunction('findParent', setupCommand.getAsString());
} catch {
success = false;
}
if (!success) {
console.log(curl.lastErrorText);
return;
}
// Register findFolder; registration sends no request.
setupCommand.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"');
setupReplacements = setupCommand.replace('ACCESS_TOKEN', curl.getVar('access_token'));
success = true;
try {
curl.addFunction('findFolder', setupCommand.getAsString());
} catch {
success = false;
}
if (!success) {
console.log(curl.lastErrorText);
return;
}
// Register findFile; registration sends no request.
setupCommand.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"');
setupReplacements = setupCommand.replace('ACCESS_TOKEN', curl.getVar('access_token'));
success = true;
try {
curl.addFunction('findFile', setupCommand.getAsString());
} catch {
success = false;
}
if (!success) {
console.log(curl.lastErrorText);
return;
}
// Register findDestination; registration sends no request.
setupCommand.setString('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('ACCESS_TOKEN', curl.getVar('access_token'));
success = true;
try {
curl.addFunction('findDestination', setupCommand.getAsString());
} catch {
success = false;
}
if (!success) {
console.log(curl.lastErrorText);
return;
}
// Register getFileDetails; registration sends no request.
setupCommand.setString('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('ACCESS_TOKEN', curl.getVar('access_token'));
success = true;
try {
curl.addFunction('getFileDetails', setupCommand.getAsString());
} catch {
success = false;
}
if (!success) {
console.log(curl.lastErrorText);
return;
}
// Register getEnterprise; registration sends no request.
setupCommand.setString('curl -X GET "https://api.box.com/2.0/users/me?fields=enterprise" -H "Authorization: Bearer ACCESS_TOKEN"');
setupReplacements = setupCommand.replace('ACCESS_TOKEN', curl.getVar('access_token'));
success = true;
try {
curl.addFunction('getEnterprise', setupCommand.getAsString());
} catch {
success = false;
}
if (!success) {
console.log(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 = true;
try {
curl.addOutput2('findParent', 'entries', 'name', '{{parent_name}}', true, 'id', 'parent_id');
} catch {
success = false;
}
if (!success) {
console.log(curl.lastErrorText);
return;
}
success = true;
try {
curl.addOutput2('findFolder', 'entries', 'name', '{{folder_name}}', true, 'id', 'folder_id');
} catch {
success = false;
}
if (!success) {
console.log(curl.lastErrorText);
return;
}
success = true;
try {
curl.addOutput2('findFile', 'entries', 'name', '{{file_name}}', true, 'id', 'file_id');
} catch {
success = false;
}
if (!success) {
console.log(curl.lastErrorText);
return;
}
success = true;
try {
curl.addOutput2('findDestination', 'entries', 'name', '{{destination_name}}', true, 'id', 'destination_id');
} catch {
success = false;
}
if (!success) {
console.log(curl.lastErrorText);
return;
}
success = true;
try {
curl.addOutput('getFileDetails', 'file_version.id', 'file_version_id');
} catch {
success = false;
}
if (!success) {
console.log(curl.lastErrorText);
return;
}
success = true;
try {
curl.addOutput('getFileDetails', 'sha1', 'file_sha1');
} catch {
success = false;
}
if (!success) {
console.log(curl.lastErrorText);
return;
}
success = true;
try {
curl.addOutput('getEnterprise', 'enterprise.id', 'enterprise_id');
} catch {
success = false;
}
if (!success) {
console.log(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.
const parentName = '/';
const folderName = 'documents';
if ((curl.getVar('parent_name') !== parentName) || ((parentName === '/') && (!curl.varDefined('parent_id')))) {
curl.setVar('parent_name', parentName);
curl.clearVar('parent_id');
curl.clearVar('folder_id');
curl.clearVar('file_id');
curl.clearVar('file_version_id');
curl.clearVar('file_sha1');
if (parentName === '/') {
curl.setVar('parent_id', '0');
}
}
if (curl.getVar('folder_name') !== folderName) {
curl.setVar('folder_name', folderName);
curl.clearVar('folder_id');
curl.clearVar('file_id');
curl.clearVar('file_version_id');
curl.clearVar('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('*');
const authorizedCommand1 = new StringBuilder();
authorizedCommand1.setString('curl -X GET "https://api.box.com/2.0/folders/{{folder_id}}?fields=id" -H "Authorization: Bearer {{access_token}}"');
const headerReplacement1 = authorizedCommand1.replace('{{access_token}}', curl.getVar('access_token'));
success = true;
try {
await curl.doYourThingAsync(authorizedCommand1.getAsString());
} catch {
success = false;
}
if ((!success) || (curl.statusCode !== 200)) {
console.log(`Box request failed. HTTP status: ${curl.statusCode}`);
console.log(`Failure reason: ${curl.failReason}`);
console.log(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.
const localPath = 'qa_data/large-document.zip';
const file = new FileAccess();
// Check the decimal size before converting so an oversized file cannot overflow int.
let sizeString: string;
try {
sizeString = file.fileSizeStr(localPath);
} catch {
console.log(file.lastErrorText);
return;
}
const sizeText = new StringBuilder();
sizeText.setString(sizeString);
const sizeMatch = new JsonObject();
if (sizeText.regexMatch('^([0-9]{1,9}|1[0-9]{9}|2000000000)$', sizeMatch, 100) !== 1) {
console.log('Choose an input between 20 MB and 2 GB for this example.');
return;
}
const fileSize = parseInt(sizeString, 10);
if (fileSize < 20971520) {
console.log('Choose an input between 20 MB and 2 GB for this example.');
return;
}
const http = new Http();
http.authToken = curl.getVar('access_token');
const response = new HttpResponse();
const request = new JsonObject();
request.updateString('folder_id', curl.getVar('folder_id'));
request.updateString('file_name', 'large-document.zip');
request.updateInt('file_size', fileSize);
success = true;
try {
await http.httpJsonAsync('POST', 'https://upload.box.com/api/2.0/files/upload_sessions', request, 'application/json', response);
} catch {
success = false;
}
if (!success) {
console.log(http.lastErrorText);
return;
}
if (response.statusCode !== 201) {
console.log(response.bodyStr);
return;
}
const session = new JsonObject();
success = true;
try {
session.load(response.bodyStr);
} catch {
success = false;
}
if (!success) {
console.log(session.lastErrorText);
return;
}
success = true;
try {
session.writeFile('qa_output/box_upload_session.json');
} catch {
success = false;
}
if (!success) {
console.log(session.lastErrorText);
return;
}
const partSize = session.intOf('part_size');
const uploadUrl = session.stringOf('session_endpoints.upload_part');
const commitUrl = session.stringOf('session_endpoints.commit');
if ((partSize <= 0) || ((uploadUrl === '') || (commitUrl === ''))) {
console.log('Invalid session response.');
return;
}
const hash = new Crypt2();
hash.hashAlgorithm = 'sha1';
hash.encodingMode = 'base64';
let fileDigest: string;
try {
fileDigest = await hash.hashFileENCAsync(localPath);
} catch {
console.log(hash.lastErrorText);
return;
}
success = true;
try {
file.fileOpen(localPath, 2147483648, 1, 3, 0);
} catch {
success = false;
}
if (!success) {
console.log(file.lastErrorText);
return;
}
const commit = new JsonObject();
const partResponse = new JsonObject();
const chunk = new BinData();
const range = new StringBuilder();
const digestHeader = new StringBuilder();
let offset = 0;
let partIndex = 0;
let partLength = 0;
let lastByte = 0;
let partDigest = '';
while (offset < fileSize) {
chunk.clear();
success = true;
try {
file.fileReadBd(partSize, chunk);
} catch {
success = false;
}
if (!success) {
console.log(file.lastErrorText);
file.fileClose();
return;
}
partLength = chunk.numBytes;
if (partLength <= 0) {
console.log('Unexpected end of file.');
file.fileClose();
return;
}
lastByte = offset + (partLength - 1);
range.clear();
range.append('bytes ');
range.appendInt(offset);
range.append('-');
range.appendInt(lastByte);
range.append('/');
range.appendInt(fileSize);
try {
partDigest = hash.hashBdENC(chunk);
} catch {
console.log(hash.lastErrorText);
file.fileClose();
return;
}
digestHeader.setString('sha=');
digestHeader.append(partDigest);
http.setRequestHeader('Digest', digestHeader.getAsString());
http.setRequestHeader('Content-Range', range.getAsString());
success = true;
try {
await http.httpBdAsync('PUT', uploadUrl, chunk, 'application/octet-stream', response);
} catch {
success = false;
}
if ((!success) || (response.statusCode !== 200)) {
console.log(`Part failed. HTTP status: ${response.statusCode}`);
console.log(response.bodyStr);
console.log('Inspect the saved session and server list_parts before retrying this part.');
file.fileClose();
return;
}
success = true;
try {
partResponse.load(response.bodyStr);
} catch {
success = false;
}
if (!success) {
file.fileClose();
return;
}
commit.i = partIndex;
// Copy the server's acknowledged part fields into the commit manifest.
commit.updateString('parts[i].part_id', partResponse.stringOf('part.part_id'));
commit.updateInt('parts[i].offset', partResponse.intOf('part.offset'));
commit.updateInt('parts[i].size', partResponse.intOf('part.size'));
commit.updateString('parts[i].sha1', partResponse.stringOf('part.sha1'));
success = true;
try {
commit.writeFile('qa_output/box_upload_parts.json');
} catch {
success = false;
}
if (!success) {
console.log(commit.lastErrorText);
file.fileClose();
return;
}
offset += partLength;
partIndex++;
}
file.fileClose();
http.removeRequestHeader('Content-Range');
digestHeader.setString('sha=');
digestHeader.append(fileDigest);
http.setRequestHeader('Digest', digestHeader.getAsString());
let attempts = 0;
let waitSeconds = 0;
const retryHeader = new StringBuilder();
const retryMatch = new JsonObject();
let completed = false;
while ((attempts < 10) && (!completed)) {
success = true;
try {
await http.httpJsonAsync('POST', commitUrl, commit, 'application/json', response);
} catch {
success = false;
}
if (!success) {
console.log(`Commit failed: ${response.statusCode}`);
console.log(response.bodyStr);
return;
}
if (response.statusCode === 201) {
completed = true;
} else {
if (response.statusCode !== 202) {
console.log(`Unexpected commit status: ${response.statusCode}`);
return;
}
// Box's asynchronous commit response supplies Retry-After in seconds.
retryHeader.setString(response.getHeaderField('Retry-After'));
if (retryHeader.regexMatch('^[0-9]{1,2}$', retryMatch, 100) !== 1) {
console.log(`Commit pending. Preserve the session and inspect Retry-After before resuming: ${retryHeader.getAsString()}`);
return;
}
waitSeconds = parseInt(retryHeader.getAsString(), 10);
if ((waitSeconds < 1) || (waitSeconds > 60)) {
console.log(`Commit pending. Resume commit after Retry-After: ${response.getHeaderField('Retry-After')}`);
return;
}
http.sleepMs(waitSeconds * 1000);
}
attempts++;
}
if (!completed) {
console.log('Commit still pending; retain session and part manifests to resume commit later.');
return;
}
console.log(`Upload committed: ${response.bodyStr}`);
}