b2_finish_large_file

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

This will return an error if there is no active upload with the given file ID, or if any of the parts of the file have not been uploaded.

Request

Request HTTP Headers

Authorization

required

An account authorization token, obtained from b2_authorize_account.

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

message

400

bad_request

No active upload for <fileId>

400

bad_request

Part <partNumber>" expected sha1 <expected sha1> but found <found sha1 >

400

bad_request

Part number <partNumber> has not been uploaded

400

bad_request

Part number <partNumber> is smaller than <minimiumPartSize> bytes

400

bad_request

Last part cannot be empty

400

bad_request

File too big. Size is <actualFileSize>, max is <maximumFileSize>.

400

bad_bucket_id

Bucket <bucketId> does not exist

400

bad_request

Wrong host name for request

401

missing_auth_token

Authorization token is missing

401

expired_auth_token

Authorization token has expired

401

bad_auth_token

Invalid authorization token

401

bad_auth_token

Authorization token for wrong cluster

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 fileId = "" // Obtained from b2_start_large_file
let apiUrl = "" // Obtained from b2_authorize_account
var partSha1Array: [String] = ["<sha1_of_part_1>","<sha1_of_part_2>", "<sha1_of_part_3>"] // See b2_upload_part 
let jsonBodyData: Dictionary<String,AnyObject> = ["fileId":fileId, "partSha1Array": partSha1Array]
if let url = NSURL(string: "\(apiUrl)/b2api/v1/b2_finish_large_file") {
    let request = NSMutableURLRequest(URL: url)
    request.HTTPMethod = "POST"
    request.addValue(accountAuthorizationToken, forHTTPHeaderField: "Authorization")
    do {
        request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(jsonBodyData, options: NSJSONWritingOptions.PrettyPrinted)
    } catch let error as NSError {
        print(error.localizedDescription)
    }
    let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
    let task = session.dataTaskWithRequest(request, completionHandler:{ (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
        if let jsonData = data {
            let json = NSString(data: jsonData, encoding:NSUTF8StringEncoding)
            print(json)
        }        
    })
    task.resume()
}

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
}