b2_finish_large_file

Converts the parts that have been uploaded into a single B2 file.

After you have uploaded the parts, use this call to combine the uploaded parts into one large file.

It may be that the call to finish a large file succeeds, but you don't know it because the request timed out, or the connection was broken. In that case, retrying will result in a 400 Bad Request response because the file is already finished. If that happens, we recommend calling b2_get_file_info to see if the file is there; if the file is there, you can count the upload as a success.

Request

Request HTTP Headers

Authorization

required

An account authorization token, obtained from b2_authorize_account. The token must have the writeFiles capability.

Request HTTP Message Body Parameters

fileId

required

The ID returned by b2_start_large_file.

partSha1Array

required

A JSON array of hex SHA1 checksums of the parts of the large file. This is a double-check that the right parts were uploaded in the right order, and that none were missed. Note that the part numbers start at 1, and the SHA1 of the part 1 is the first string in the array, at index 0.

[
  "40d2b810f4b3978444b98d44a01cbc2680432726",
  "956a86f77f2fd6181fcec963d3244689b720d845"
]

Response

Response HTTP Status 200

Large file successfully finished. The JSON response will contain:

fileId

The unique identifier for this version of this file. Used with b2_get_file_info, b2_download_file_by_id, and b2_delete_file_version.

fileName

The name of this file, which can be used with b2_download_file_by_name.

accountId

Your account ID.

bucketId

The bucket that the file is in.

contentLength

The number of bytes stored in the file.

contentSha1

Large files do not have a SHA1 checksum. The value will always be "none".

contentType

The MIME type of the file.

fileInfo

The custom information that was uploaded with the file. This is a JSON object, holding the name/value pairs that were uploaded with the file.

action

Always "upload".

uploadTimestamp

This is a UTC time when this file was uploaded. It is a base 10 number of milliseconds since midnight, January 1, 1970 UTC. This fits in a 64 bit integer such as the type "long" in the programming language Java. It is intended to be compatible with Java's time long. For example, it can be passed directly into the java call Date.setTime(long time).

Response Errors

Large file not finished. If possible the server will return a JSON error structure. Errors include:

status

code

description

400

bad_request

The request had the wrong fields or illegal values. The message returned with the error will describe the problem.

400

bad_bucket_id

Bucket does not exist

401

unauthorized

The auth token used is valid, but does not authorize this call with these parameters. The capabilities of an auth token are determined by the application key used with b2_authorize_account.

401

bad_auth_token

The auth token used is not valid. Call b2_authorize_account again to either get a new one, or an error message describing the problem.

401

expired_auth_token

The auth token used has expired. Call b2_authorize_account again to get a new one.

API Versions

v1: Application keys (July 26, 2018)

Incompatible change: After calling b2_authorize_account with an application key that does not have the right permissions, this call will return a 401 Unauthorized.

v1: Original release (September 22, 2015)

Sample Code

Code

FILE_ID=''; # Provided by b2_start_large_file
ACCOUNT_AUTHORIZATION_TOKEN=''; # Provided by b2_authorize_acount
PART_SHA1_ARRAY=('<sha1_part_1>' '<sha1_part_2>' '<sha1_part_3>');

# Create JSON
JSON='{ "partSha1Array":[';
for sha1 in "${PART_SHA1_ARRAY[@]}"; do
	JSON+="\"$sha1\",";
done
JSON="${JSON%?}";
JSON+="], \"fileId\":\"$FILE_ID\"}";

# Do the post
curl \
    -H "Authorization: $ACCOUNT_AUTHORIZATION_TOKEN" \
    -d "$JSON" \
    "$API_URL/b2api/v1/b2_finish_large_file"

Output

{
  "accountId": "YOUR_ACOUNT_ID",
  "action": "upload",
  "bucketId": "e73ede9c9c8412db49f60715",
  "contentLength": 208158542,
  "contentSha1": "none",
  "contentType": "b2/x-auto",
  "fileId": "4_ze73ede9c9c8412db49f60715_f100b4e93fbae6252_d20150824_m224353_c900_v8881000_t0001",
  "fileInfo": {},
  "fileName": "bigfile.dat",
  "uploadTimestamp": 1460162909000
}

Code

import java.io.*;
import java.util.*;
import javax.json.*;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.URL;

String fileId = ""; // Provided by b2_start_large_file
String accountAuthorizationToken = ""; // Provided by b2_authorize_account
String apiUrl = ""; // Provided by b2_authorize_account

ArrayList<String> partSha1Array = {"<sha1_of_part_1>","sha1_of_part_2","sha1_of_part_3"}; // See b2_upload_part

// Create Json
JsonArrayBuilder jsonArrayOfSha1Builder = Json.createArrayBuilder();
Enumeration<String> enumerator = Collections.enumeration(partSha1Array);
while(enumerator.hasMoreElements()) {
    jsonArrayOfSha1Builder.add(enumerator.nextElement());
}
JsonObject finishLargeFileJsonObj = Json.createObjectBuilder()
        .add("fileId", fileId)
        .add("partSha1Array", jsonArrayOfSha1Builder)
        .build();

StringWriter sw = new StringWriter();
JsonWriter jw = Json.createWriter(sw);
jw.write(finishLargeFileJsonObj);
jw.close();
postData = sw.toString();

try {
    URL url = new URL(apiUrl + "/b2api/v1/b2_finish_large_file");
    connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Authorization", accountAuthorizationToken);
    connection.setRequestProperty("Charset", "UTF-8");
    connection.setRequestProperty("Content-Type", "application/json");
    connection.setDoOutput(true);
    DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
    dataOutputStream.writeBytes(postData);
    dataOutputStream.close();
    String jsonResponse = myInputStreamReader(connection.getInputStream());
    System.out.println(jsonResponse);
} catch(Exception ex) {
    ex.printStackTrace();
}

// Input stream reader example. 
static public String myInputStreamReader(InputStream in) throws IOException {
    InputStreamReader reader = new InputStreamReader(in);
    StringBuilder sb = new StringBuilder();
    int c = reader.read();
    while (c != -1) {
        sb.append((char)c);
        c = reader.read();
    }
    reader.close();
    return sb.toString();
}

Output

{
  "accountId": "YOUR_ACOUNT_ID",
  "action": "upload",
  "bucketId": "e73ede9c9c8412db49f60715",
  "contentLength": 208158542,
  "contentSha1": "none",
  "contentType": "b2/x-auto",
  "fileId": "4_ze73ede9c9c8412db49f60715_f100b4e93fbae6252_d20150824_m224353_c900_v8881000_t0001",
  "fileInfo": {},
  "fileName": "bigfile.dat",
  "uploadTimestamp": 1460162909000
}

Code

import base64
import json
import urllib2

account_authorization_token = "" # Provided by b2_authorize_account
file_id = "" # Provided by b2_start_large_file
part_sha1_array = ["<sha1_of_part_1>","<sha1_of_part_2>","<sha1_of_part_3>"] # See b2_upload_part
request = urllib2.Request(
    '%s/b2api/v1/b2_finish_large_file' % api_url,
    json.dumps({ 'fileId' : file_id, 'partSha1Array': part_sha1_array}),
    headers = { 'Authorization': account_authorization_token }
)
response = urllib2.urlopen(request)
response_data = json.loads(response.read())
response.close()

Output

{
  "accountId": "YOUR_ACOUNT_ID",
  "action": "upload",
  "bucketId": "e73ede9c9c8412db49f60715",
  "contentLength": 208158542,
  "contentSha1": "none",
  "contentType": "b2/x-auto",
  "fileId": "4_ze73ede9c9c8412db49f60715_f100b4e93fbae6252_d20150824_m224353_c900_v8881000_t0001",
  "fileInfo": {},
  "fileName": "bigfile.dat",
  "uploadTimestamp": 1460162909000
}

Code

import Foundation

let apiUrl = "" // Obtained from b2_authorize_account
let accountAuthorizationToken = "" // Provided by b2_authorize_account
let fileId = "" // Obtained from b2_start_large_file


let partSha1Array = ["<sha1_of_part_1>","<sha1_of_part_2>", "<sha1_of_part_3>"] // See b2_upload_part
let jsonBodyData: [String:Any] = ["fileId": fileId, "partSha1Array": partSha1Array]
let url = URL(string: "\(apiUrl)/b2api/v1/b2_finish_large_file")

// Create the request
var request = URLRequest(url: url!)
request.httpMethod = "POST"
request.addValue(accountAuthorizationToken, forHTTPHeaderField: "Authorization")
do {
	request.httpBody = try JSONSerialization.data(withJSONObject: jsonBodyData, options: .prettyPrinted)
} catch (let error) {
	print(error.localizedDescription)
}

// Create the task
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
	if let data = data {
		let json = String(data: data, encoding: .utf8)
		print("\(json!)")
	}
}

// Start the task
task.resume()

// Swift 4.1 (swiftlang-902.0.48 clang-902.0.37.1) Xcode 9.3.1 (9E501)

Output

{
  "accountId": "YOUR_ACOUNT_ID",
  "action": "upload",
  "bucketId": "e73ede9c9c8412db49f60715",
  "contentLength": 208158542,
  "contentSha1": "none",
  "contentType": "b2/x-auto",
  "fileId": "4_ze73ede9c9c8412db49f60715_f100b4e93fbae6252_d20150824_m224353_c900_v8881000_t0001",
  "fileInfo": {},
  "fileName": "bigfile.dat",
  "uploadTimestamp": 1460162909000
}

Code

require 'json'
require 'net/http'

file_id = "" # Provided by b2_start_large_file
sha1_of_parts = ["<sha1 of part 1>","<sha1 of part 2>"] # See b2_upload_part
account_authorization_token = "" # Provided by b2_authorize_account
uri = URI.join("#{api_url}/b2api/v1/b2_finish_large_file")
req = Net::HTTP::Post.new(uri)
req.add_field("Authorization","#{account_authorization_token}")
# NOTE: The array of sha1 for each part you sent using b2_upload_part
params = {"fileId" => fileId, "partSha1Array" => ["<sha1_of_part_1>","<sha1_of_part_2>"]}
jkljreq.body = dump(params)
http = Net::HTTP.new(req.uri.host, req.uri.port)
http.use_ssl = true
res = http.start {|http| http.request(req)}
case res
when Net::HTTPSuccess then
    res.body
when Net::HTTPRedirection then
    fetch(res['location'], limit - 1)
else
    res.error!
end

Output

{
  "accountId": "YOUR_ACOUNT_ID",
  "action": "upload",
  "bucketId": "e73ede9c9c8412db49f60715",
  "contentLength": 208158542,
  "contentSha1": "none",
  "contentType": "b2/x-auto",
  "fileId": "4_ze73ede9c9c8412db49f60715_f100b4e93fbae6252_d20150824_m224353_c900_v8881000_t0001",
  "fileInfo": {},
  "fileName": "bigfile.dat",
  "uploadTimestamp": 1460162909000
}

Code

using System;
using System.Net;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;         

String authorizationToken = ""; // Provided by b2_authorize_account
String fileId = ""; // Provided by b2_start_large_file
String apiUrl = ""; // Provided by b2_authorize_account
ArrayList partSha1Array = {"<sha1_part1>","<sha1_part2>","<sha1_part3>"}; // See b2_upload_part

// Create a request object and copy it to the memory stream.
B2FinishLargeFileRequest finishLargeFileData = new B2FinishLargeFileRequest();
finishLargeFileData.fileId = fileId;
finishLargeFileData.partSha1Array = partSha1Array;
MemoryStream finishLargeFileMemStream = new MemoryStream();
DataContractJsonSerializer finishLargeFileSerializer = new DataContractJsonSerializer(typeof(B2FinishLargeFileRequest));
finishLargeFileSerializer.WriteObject(finishLargeFileMemStream, finishLargeFileData);

HttpWebRequest finishLargeFileRequest = (HttpWebRequest)WebRequest.Create(authData.apiUrl + "/b2api/v1/b2_finish_large_file");
finishLargeFileRequest.Method = "POST";
finishLargeFileRequest.Headers.Add("Authorization", authorizationToken);
finishLargeFileRequest.ContentType = "application/json; charset=utf-8";
finishLargeFileRequest.ContentLength = finishLargeFileMemStream.Length;
finishLargeFileMemStream.WriteTo(finishLargeFileRequest.GetRequestStream());
HttpWebResponse finishLargeFileResponse = null;
try
{
    finishLargeFileResponse = (HttpWebResponse)finishLargeFileRequest.GetResponse();
}
catch (WebException e)
{
    using (WebResponse r = e.Response)
    {
        HttpWebResponse httpResponse = (HttpWebResponse)r;
        Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
        using (Stream dataE = r.GetResponseStream())
        using (var reader = new StreamReader(dataE))
        {
            string text = reader.ReadToEnd();
            Console.WriteLine(text);
        }
    }
}


// Class used with Json Serialization
[DataContract]
class B2FinishLargeFileRequest
{
    [DataMember]
    public String fileId;
    [DataMember]
    public ArrayList partSha1Array;
}

Output

under construction

Code

<?php

$api_url = ""; // Obtained from b2_authorize_account
$file_id = ""; // Obtained from b2_start_large_file
$sha1_of_parts = ["<sha1_of_first_part>","<sha1_of_second_part>","<sha1_of_third_part>"]; // See b2_upload_part
$session = curl_init($api_url . "/b2api/v1/b2_finish_large_file");

// Add headers
$headers = array();
$headers[] = "Accept: application/json";
$headers[] = "Authorization: " . $account_auth_token;

// Send over the wire
curl_setopt($session, CURLOPT_POSTFIELDS, $post_fields); 
curl_setopt($session, CURLOPT_HTTPHEADER, $headers);  // Add headers
curl_setopt($session, CURLOPT_RETURNTRANSFER, true); // Receive server response
$server_output = curl_exec($session);
curl_close ($session);
print $server_output;

?>

Output

{
  "accountId": "YOUR_ACOUNT_ID",
  "action": "upload",
  "bucketId": "e73ede9c9c8412db49f60715",
  "contentLength": 208158542,
  "contentSha1": "none",
  "contentType": "b2/x-auto",
  "fileId": "4_ze73ede9c9c8412db49f60715_f100b4e93fbae6252_d20150824_m224353_c900_v8881000_t0001",
  "fileInfo": {},
  "fileName": "bigfile.dat",
  "uploadTimestamp": 1460162909000
}