Unicode C++ Requires Chilkat v11.5.0+
Unicode C++
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 Unicode C++ Downloads
#include <CkHttpCurlW.h>
#include <CkStringBuilderW.h>
#include <CkFileAccessW.h>
#include <CkJsonObjectW.h>
#include <CkHttpW.h>
#include <CkHttpResponseW.h>
#include <CkCrypt2W.h>
#include <CkBinDataW.h>
void ChilkatSample(void)
{
bool success = false;
// Requires Chilkat 11.5.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.
CkHttpCurlW curl;
curl.SetVar(L"access_token",L"BOX_ACCESS_TOKEN");
curl.SetVar(L"parent_name",L"/");
curl.SetVar(L"folder_name",L"images");
curl.SetVar(L"file_name",L"penguins.jpg");
curl.SetVar(L"destination_name",L"archive");
// Box's fixed root ID is an implementation detail; callers supply names.
curl.SetVar(L"parent_id",L"0");
CkStringBuilderW setupCommand;
int setupReplacements;
// Register findParent; registration sends no request.
setupCommand.SetString(L"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(L"ACCESS_TOKEN",curl.getVar(L"access_token"));
success = curl.AddFunction(L"findParent",setupCommand.getAsString());
if (success != true) {
wprintf(L"%s\n",curl.lastErrorText());
return;
}
// Register findFolder; registration sends no request.
setupCommand.SetString(L"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(L"ACCESS_TOKEN",curl.getVar(L"access_token"));
success = curl.AddFunction(L"findFolder",setupCommand.getAsString());
if (success != true) {
wprintf(L"%s\n",curl.lastErrorText());
return;
}
// Register findFile; registration sends no request.
setupCommand.SetString(L"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(L"ACCESS_TOKEN",curl.getVar(L"access_token"));
success = curl.AddFunction(L"findFile",setupCommand.getAsString());
if (success != true) {
wprintf(L"%s\n",curl.lastErrorText());
return;
}
// Register findDestination; registration sends no request.
setupCommand.SetString(L"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(L"ACCESS_TOKEN",curl.getVar(L"access_token"));
success = curl.AddFunction(L"findDestination",setupCommand.getAsString());
if (success != true) {
wprintf(L"%s\n",curl.lastErrorText());
return;
}
// Register getFileDetails; registration sends no request.
setupCommand.SetString(L"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(L"ACCESS_TOKEN",curl.getVar(L"access_token"));
success = curl.AddFunction(L"getFileDetails",setupCommand.getAsString());
if (success != true) {
wprintf(L"%s\n",curl.lastErrorText());
return;
}
// Register getEnterprise; registration sends no request.
setupCommand.SetString(L"curl -X GET \"https://api.box.com/2.0/users/me?fields=enterprise\" -H \"Authorization: Bearer ACCESS_TOKEN\"");
setupReplacements = setupCommand.Replace(L"ACCESS_TOKEN",curl.getVar(L"access_token"));
success = curl.AddFunction(L"getEnterprise",setupCommand.getAsString());
if (success != true) {
wprintf(L"%s\n",curl.lastErrorText());
return;
}
// Initial name selections. AddOutput2 stores these WHERE values literally.
success = curl.AddOutput2(L"findParent",L"entries",L"name",curl.getVar(L"parent_name"),true,L"id",L"parent_id");
if (success != true) {
wprintf(L"%s\n",curl.lastErrorText());
return;
}
success = curl.AddOutput2(L"findFolder",L"entries",L"name",curl.getVar(L"folder_name"),true,L"id",L"folder_id");
if (success != true) {
wprintf(L"%s\n",curl.lastErrorText());
return;
}
success = curl.AddOutput2(L"findFile",L"entries",L"name",curl.getVar(L"file_name"),true,L"id",L"file_id");
if (success != true) {
wprintf(L"%s\n",curl.lastErrorText());
return;
}
success = curl.AddOutput2(L"findDestination",L"entries",L"name",curl.getVar(L"destination_name"),true,L"id",L"destination_id");
if (success != true) {
wprintf(L"%s\n",curl.lastErrorText());
return;
}
success = curl.AddOutput(L"getFileDetails",L"file_version.id",L"file_version_id");
if (success != true) {
wprintf(L"%s\n",curl.lastErrorText());
return;
}
success = curl.AddOutput(L"getFileDetails",L"sha1",L"file_sha1");
if (success != true) {
wprintf(L"%s\n",curl.lastErrorText());
return;
}
success = curl.AddOutput(L"getEnterprise",L"enterprise.id",L"enterprise_id");
if (success != true) {
wprintf(L"%s\n",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 wchar_t *parentName = L"/";
const wchar_t *folderName = L"documents";
if ((curl.getVar(L"parent_name") != parentName) || ((parentName == L"/") && (curl.VarDefined(L"parent_id") == false))) {
curl.SetVar(L"parent_name",parentName);
curl.ClearVar(L"parent_id");
curl.ClearVar(L"folder_id");
curl.ClearVar(L"file_id");
curl.ClearVar(L"file_version_id");
curl.ClearVar(L"file_sha1");
if (parentName == L"/") {
curl.SetVar(L"parent_id",L"0");
}
else {
success = curl.AddOutput2(L"findParent",L"entries",L"name",curl.getVar(L"parent_name"),true,L"id",L"parent_id");
if (success != true) {
wprintf(L"%s\n",curl.lastErrorText());
return;
}
}
}
if (curl.getVar(L"folder_name") != folderName) {
curl.SetVar(L"folder_name",folderName);
curl.ClearVar(L"folder_id");
curl.ClearVar(L"file_id");
curl.ClearVar(L"file_version_id");
curl.ClearVar(L"file_sha1");
success = curl.AddOutput2(L"findFolder",L"entries",L"name",curl.getVar(L"folder_name"),true,L"id",L"folder_id");
if (success != true) {
wprintf(L"%s\n",curl.lastErrorText());
return;
}
}
// 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(L"*");
CkStringBuilderW authorizedCommand1;
authorizedCommand1.SetString(L"curl -X GET \"https://api.box.com/2.0/folders/{{folder_id}}?fields=id\" -H \"Authorization: Bearer {{access_token}}\"");
int headerReplacement1 = authorizedCommand1.Replace(L"{{access_token}}",curl.getVar(L"access_token"));
success = curl.DoYourThing(authorizedCommand1.getAsString());
if ((success != true) || (curl.get_StatusCode() != 200)) {
wprintf(L"Box request failed. HTTP status: %d\n",curl.get_StatusCode());
wprintf(L"Failure reason: %d\n",curl.get_FailReason());
wprintf(L"%s\n",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 wchar_t *localPath = L"qa_data/large-document.zip";
CkFileAccessW file;
// Check the decimal size before converting so an oversized file cannot overflow int.
const wchar_t *sizeString = file.fileSizeStr(localPath);
if (file.get_LastMethodSuccess() != true) {
wprintf(L"%s\n",file.lastErrorText());
return;
}
CkStringBuilderW sizeText;
sizeText.SetString(sizeString);
CkJsonObjectW sizeMatch;
if (sizeText.RegexMatch(L"^([0-9]{1,9}|1[0-9]{9}|2000000000)$",sizeMatch,100) != 1) {
wprintf(L"Choose an input between 20 MB and 2 GB for this example.\n");
return;
}
int fileSize = wcstol(sizeString);
if (fileSize < 20971520) {
wprintf(L"Choose an input between 20 MB and 2 GB for this example.\n");
return;
}
CkHttpW http;
http.put_AuthToken(curl.getVar(L"access_token"));
CkHttpResponseW response;
CkJsonObjectW request;
request.UpdateString(L"folder_id",curl.getVar(L"folder_id"));
request.UpdateString(L"file_name",L"large-document.zip");
request.UpdateInt(L"file_size",fileSize);
success = http.HttpJson(L"POST",L"https://upload.box.com/api/2.0/files/upload_sessions",request,L"application/json",response);
if (success != true) {
wprintf(L"%s\n",http.lastErrorText());
return;
}
if (response.get_StatusCode() != 201) {
wprintf(L"%s\n",response.bodyStr());
return;
}
CkJsonObjectW session;
success = session.Load(response.bodyStr());
if (success != true) {
wprintf(L"%s\n",session.lastErrorText());
return;
}
success = session.WriteFile(L"qa_output/box_upload_session.json");
if (success != true) {
wprintf(L"%s\n",session.lastErrorText());
return;
}
int partSize = session.IntOf(L"part_size");
const wchar_t *uploadUrl = session.stringOf(L"session_endpoints.upload_part");
const wchar_t *commitUrl = session.stringOf(L"session_endpoints.commit");
if ((partSize <= 0) || (uploadUrl == L"") || (commitUrl == L"")) {
wprintf(L"Invalid session response.\n");
return;
}
CkCrypt2W hash;
hash.put_HashAlgorithm(L"sha1");
hash.put_EncodingMode(L"base64");
const wchar_t *fileDigest = hash.hashFileENC(localPath);
if (hash.get_LastMethodSuccess() != true) {
wprintf(L"%s\n",hash.lastErrorText());
return;
}
success = file.FileOpen(localPath,2147483648,1,3,0);
if (success != true) {
wprintf(L"%s\n",file.lastErrorText());
return;
}
CkJsonObjectW commit;
CkJsonObjectW partResponse;
CkBinDataW chunk;
CkStringBuilderW range;
CkStringBuilderW digestHeader;
int offset = 0;
int partIndex = 0;
int partLength;
int lastByte;
const wchar_t *partDigest = 0;
while (offset < fileSize) {
chunk.Clear();
success = file.FileReadBd(partSize,chunk);
if (success != true) {
wprintf(L"%s\n",file.lastErrorText());
file.FileClose();
return;
}
partLength = chunk.get_NumBytes();
if (partLength <= 0) {
wprintf(L"Unexpected end of file.\n");
file.FileClose();
return;
}
lastByte = offset + (partLength - 1);
range.Clear();
range.Append(L"bytes ");
range.AppendInt(offset);
range.Append(L"-");
range.AppendInt(lastByte);
range.Append(L"/");
range.AppendInt(fileSize);
partDigest = hash.hashBdENC(chunk);
if (hash.get_LastMethodSuccess() != true) {
wprintf(L"%s\n",hash.lastErrorText());
file.FileClose();
return;
}
digestHeader.SetString(L"sha=");
digestHeader.Append(partDigest);
http.SetRequestHeader(L"Digest",digestHeader.getAsString());
http.SetRequestHeader(L"Content-Range",range.getAsString());
success = http.HttpBd(L"PUT",uploadUrl,chunk,L"application/octet-stream",response);
if ((success != true) || (response.get_StatusCode() != 200)) {
wprintf(L"Part failed. HTTP status: %d\n",response.get_StatusCode());
wprintf(L"%s\n",response.bodyStr());
wprintf(L"Inspect the saved session and server list_parts before retrying this part.\n");
file.FileClose();
return;
}
success = partResponse.Load(response.bodyStr());
if (success != true) {
file.FileClose();
return;
}
commit.put_I(partIndex);
// Copy the server's acknowledged part fields into the commit manifest.
commit.UpdateString(L"parts[i].part_id",partResponse.stringOf(L"part.part_id"));
commit.UpdateInt(L"parts[i].offset",partResponse.IntOf(L"part.offset"));
commit.UpdateInt(L"parts[i].size",partResponse.IntOf(L"part.size"));
commit.UpdateString(L"parts[i].sha1",partResponse.stringOf(L"part.sha1"));
success = commit.WriteFile(L"qa_output/box_upload_parts.json");
if (success != true) {
wprintf(L"%s\n",commit.lastErrorText());
file.FileClose();
return;
}
offset = offset + partLength;
partIndex = partIndex + 1;
}
file.FileClose();
http.RemoveRequestHeader(L"Content-Range");
digestHeader.SetString(L"sha=");
digestHeader.Append(fileDigest);
http.SetRequestHeader(L"Digest",digestHeader.getAsString());
int attempts = 0;
int waitSeconds;
CkStringBuilderW retryHeader;
CkJsonObjectW retryMatch;
bool completed = false;
while ((attempts < 10) && (completed == false)) {
success = http.HttpJson(L"POST",commitUrl,commit,L"application/json",response);
if (success != true) {
wprintf(L"Commit failed: %d\n",response.get_StatusCode());
wprintf(L"%s\n",response.bodyStr());
return;
}
if (response.get_StatusCode() == 201) {
completed = true;
}
else {
if (response.get_StatusCode() != 202) {
wprintf(L"Unexpected commit status: %d\n",response.get_StatusCode());
return;
}
// Box's asynchronous commit response supplies Retry-After in seconds.
retryHeader.SetString(response.getHeaderField(L"Retry-After"));
if (retryHeader.RegexMatch(L"^[0-9]{1,2}$",retryMatch,100) != 1) {
wprintf(L"Commit pending. Preserve the session and inspect Retry-After before resuming: %s\n",retryHeader.getAsString());
return;
}
waitSeconds = wcstol(retryHeader.getAsString());
if ((waitSeconds < 1) || (waitSeconds > 60)) {
wprintf(L"Commit pending. Resume commit after Retry-After: %s\n",response.getHeaderField(L"Retry-After"));
return;
}
http.SleepMs(waitSeconds * 1000);
}
attempts = attempts + 1;
}
if (completed == false) {
wprintf(L"Commit still pending; retain session and part manifests to resume commit later.\n");
return;
}
wprintf(L"Upload committed: %s\n",response.bodyStr());
}