b2_start_large_file

Prepares for uploading the parts of a large file.

Request

Request HTTP Headers

Authorization

required

An account authorization token, obtained from b2_authorize_account.

Request HTTP Message Body Parameters

bucketId

required

The ID of the bucket that the file will go in.

fileName

required

The name of the file. See Files for requirements on file names.

contentType

required

The MIME type of the content of the file, which will be returned in the Content-Type header when downloading the file. Use the Content-Type b2/x-auto to automatically set the stored Content-Type post upload. In the case where a file extension is absent or the lookup fails, the Content-Type is set to application/octet-stream. The Content-Type mappings can be perused here.

fileInfo

optional

A JSON object holding the name/value pairs for the custom file info.

If the original source of the file being uploaded has a last modified time concept, Backblaze recommends using src_last_modified_millis as the name, and a string holding the base 10 number 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).

If the caller knows the SHA1 of the entire large file being uploaded, Backblaze recommends using large_file_sha1 as the name, and a 40 byte hex string representing the SHA1.

To set the Content-Disposition header provided when the file is downloaded, set 'b2-content-disposition'. (It may be overridden by a value given in the download request.) The value must match the grammar specified in RFC 6266. Parameter continuations are not supported. 'Extended-value's are supported for charset 'UTF-8' (case-insensitive) when the language is empty. Note that this file info will not be included in downloads as a x-bz-info-b2-content-disposition header. Instead, it (or the value specified in a request) will be in the Content-Disposition.

Example: { "src_last_modified_millis" : "1452802803026", "large_file_sha1" : "a3195dc1e7b46a2ff5da4b3c179175b75671e80d", "color": "blue" }

The file name and file info must fit, along with the other necessary headers, within a 7,000 byte limit. This ensures that when the file is downloaded that all of the information can be included in the headers.

Response

Response HTTP Status 200

Large file successfully started. The JSON response will contain:

fileId

The unique identifier for the file. Used with b2_upload_part, b2_finish_large_file, and b2_cancel_large_file.

fileName

The name of this file.

accountId

Your account ID.

bucketId

The bucket that the file will be in.

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.

uploadTimestamp

This is a UTC time when this file was started. 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

Unable to start large file. If possible the server will return a JSON error structure. Errors include:

status

code

message

400

bad_bucket_id

Not a valid bucket_id: <bucketId>

400

bad_request

File names must contain at least one character

400

bad_request

File names in UTF8 must be no more than 1000 bytes

400

bad_request

File names must not start with '/'

400

bad_request

File names must not end with '/'

400

bad_request

File names must not contain '\'

400

bad_request

File names must not contain DELETE

400

bad_request

File names must not contain '//'

400

bad_request

Maximum number of file info entries is 10

400

bad_request

File info name too long: <name>

400

bad_request

File info value too long: <value>

400

bad_request

Illegal file info name: " + <value>

400

bad_request

Total size of file name and file info headers is <totalSize>, which is over the max of 7000

400

bad_request

File names segment must not be more than 250 bytes

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

ACCOUNT_AUTHORIZATION_TOKEN=''; # Provided by b2_authorize_account
BUCKET_ID=''; # The ID of bucket you want the file to land in. The bucket ID is provided by b2_create_bucket and b2_list_buckets
FILE_NAME=''; # File name as it will appear on B2
CONTENT_TYPE=''; # Content type of the file. 
curl \
    -H "Authorization: $ACCOUNT_AUTHORIZATION_TOKEN" \
    -d "`printf '{"fileName":"%s", "bucketId":"%s", "contentType":"%s"}' $B2_FILE_NAME $BUCKET_ID $CONTENT_TYPE`" \
    "$API_URL/b2api/v1/b2_start_large_file";

Output

{
  "accountId": "YOUR_ACCOUNT_ID",
  "bucketId": "e73ede9c9c8412db49f60715",
  "contentType": "b2/x-auto",
  "fileId": "4_za71f544e781e6891531b001a_f200ec353a2184825_d20160409_m004829_c000_v0001016_t0028",
  "fileInfo": {},
  "fileName": "bigfile.dat",
  "uploadTimestamp": 1460162909000
}

Code

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

String apiUrl = ""; // Provided by b2_authorize_account
String bucketId = ""; // The ID of the destination bucket. The bucket ID is provided by b2_create_bucket, b2_list_buckets. 
String fileName = ""; // Name of the file as it will appear in B2
String fileContentType = ""; // Content type of the file
String accountAuthorizationToken = ""l // Provided by b2_authorize_account

// Create a JSON object
JsonObject startLargeFileJsonObj = Json.createObjectBuilder()
        .add("fileName", fileName)
        .add("contentType", fileContentType)
        .add("bucketId", bucketId)
        .build();

// Convert the JSON object to a string
StringWriter sw = new StringWriter();
JsonWriter jw = Json.createWriter(sw);
jw.writeObject(startLargeFileJsonObj);
jw.close();
String postData = sw.toString();

// Send it over the wire
try {
    URL url = new URL(apiUrl + "/b2api/v1/b2_start_large_file");
    connection = (HttpURLConnection)url.openConnection();
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Authorization", accountAuthorizationToken);
    connection.setRequestProperty("Content-Type", "application/json");
    connection.setRequestProperty("Charset", "UTF-8");
    connection.setRequestProperty("Content-Length", Integer.toString(postData.length()));
    connection.setDoOutput(true);
    DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
    dataOutputStream.writeBytes(postData);
	String jsonResponse = myInputStreamReader(connection.getInputStream());
	System.out.println(jsonResponse);   
} catch (Exception e) {
    e.printStackTrace();
} finally {
    connection.disconnect();
}

// 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_ACCOUNT_ID",
  "bucketId": "e73ede9c9c8412db49f60715",
  "contentType": "b2/x-auto",
  "fileId": "4_za71f544e781e6891531b001a_f200ec353a2184825_d20160409_m004829_c000_v0001016_t0028",
  "fileInfo": {},
  "fileName": "bigfile.dat",
  "uploadTimestamp": 1460162909000
}

Code

import base64
import json
import urllib2

file_name = "" # Name of the file as it appears in B2
content_type = "" # Content Type of the file
bucket_id = "" # The ID of the bucket provided by b2_create_bucket or b2_list_buckets
request = urllib2.Request(
    '%s/b2api/v1/b2_start_large_file' % api_url,
    json.dumps({ 'fileName': file_name, 'contentType': content_type, 'bucketId': bucket_id }),
    headers = { 'Authorization': account_authorization_token }
)
response = urllib2.urlopen(request)
response_data = json.loads(response.read())
response.close() 

Output

{
  "accountId": "YOUR_ACCOUNT_ID",
  "bucketId": "e73ede9c9c8412db49f60715",
  "contentType": "b2/x-auto",
  "fileId": "4_za71f544e781e6891531b001a_f200ec353a2184825_d20160409_m004829_c000_v0001016_t0028",
  "fileInfo": {},
  "fileName": "bigfile.dat",
  "uploadTimestamp": 1460162909000
}

Code


import Foundation

let apiUrl = "" // Provided by b2_authorize_account
let fileName = "" // The file name of the file to upload
let accountAuthorizationToken = "" // Provided by b2_authorize_account
let bucketId = "" // Provided by b2_create_bucket, b2_list_buckets
let contentType = "" // The content type of the file. See b2_start_large_file documentation for more information.
var requestBody: Dictionary<String,AnyObject> = ["fileName":fileName, "bucketId":bucketId, "contentType":contentType];
let request = NSMutableURLRequest(URL:NSURL(string: "\(apiUrl)")!.URLByAppendingPathComponent("/b2api/v1/b2_start_large_file"))
request.HTTPMethod = "POST"
request.addValue(accountAuthorizationToken!, forHTTPHeaderField: "Authorization")
do {
    request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(requestBody, 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_ACCOUNT_ID",
  "bucketId": "e73ede9c9c8412db49f60715",
  "contentType": "b2/x-auto",
  "fileId": "4_za71f544e781e6891531b001a_f200ec353a2184825_d20160409_m004829_c000_v0001016_t0028",
  "fileInfo": {},
  "fileName": "bigfile.dat",
  "uploadTimestamp": 1460162909000
}

Code

require 'json'
require 'net/http'

bucket_id = "" # Provided by b2_create_bucket, b2_list_buckets
file_name = "" # File to be uploaded
content_type = "" # The content type of the file. See b2_start_large_file documentation for more information.
account_authorization_token = "" # Provided by b2_authorize_account
uri = URI.join("#{api_url}/b2api/v1/b2_start_large_file")
req = Net::HTTP::Post.new(uri)
req.add_field("Authorization","#{account_authorization_token}")
req.body = "{\"bucketId\":\"#{bucket_id}\",\"fileName\":\"#{file_name}\",\"contentType\":\"#{content_type}\"}"
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_ACCOUNT_ID",
  "bucketId": "e73ede9c9c8412db49f60715",
  "contentType": "b2/x-auto",
  "fileId": "4_za71f544e781e6891531b001a_f200ec353a2184825_d20160409_m004829_c000_v0001016_t0028",
  "fileInfo": {},
  "fileName": "bigfile.dat",
  "uploadTimestamp": 1460162909000
}

Code

using System;
using System.Net;
using System.Text;
using System.IO;

String bucketId = ""; // Provided by b2_create_bucket or b2_list_buckets
String fileName = ""; // Name of the file as it will appear in B2
String contentType = ""; // Content type of the file
String apiUrl = ""; // Provided by b2_authorize_account
String authorizationToken = ""; // Provided by b2_authorize_account

// Setup JSON to post.
String startLargeFileJsonStr = "{\"bucketId\":\"" + bucketId + "\",\"fileName\":\"" + fileName + "\",\"contentType\":\"" + contentType + "\"}";
byte[] jsonData = Encoding.UTF8.GetBytes(startLargeFileJsonStr);

// Send over the wire
HttpWebRequest startLargeFileRequest = (HttpWebRequest)WebRequest.Create(apiUrl + "/b2api/v1/b2_start_large_file");
startLargeFileRequest.Method = "POST";
startLargeFileRequest.Headers.Add("Authorization", authorizationToken);
startLargeFileRequest.ContentType = "application/json; charset=utf-8";
startLargeFileRequest.ContentLength = jsonData.Length;
using (Stream stream = startLargeFileRequest.GetRequestStream())
{
    stream.Write(jsonData, 0, jsonData.Length);
    stream.Close();
}

// Handle the response and print the json
try
{
    HttpWebResponse startLargeFileResponse = (HttpWebResponse)startLargeFileRequest.GetResponse();
    using(StringReader responseReader = new StreamReader(startLargeFileResponse.GetResponseStream()))
    {
    	String json = responseReader.ReadToEnd();
    	Console.WriteLine(json);
    }
    startLargeFileResponse.Close();
}
catch (WebException e)
{
    using (HttpWebResponse errorResponse = (HttpWebResponse)e.Response)
    {
        Console.WriteLine("Error code: {0}", errorResponse.StatusCode);
        using (StreamReader reader = new StreamReader(errorResponse.GetResponseStream()))
        {
            String text = reader.ReadToEnd();
            Console.WriteLine(text);
        }
    }
}

Output

under construction

Code

<?php

$file_name = ""; // File to be uploaded
$bucket_id = ""; // Provided by b2_create_bucket, b2_list_buckets
$content_type = ""; // The content type of the file. See b2_start_large_file documentation for more information.
// Construct the JSON to post
$data = array("fileName" => $file_name, "bucketId" => $bucket_id, "contentType" => $content_type);
$post_fields = json_encode($data);

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

// Setup curl to do the post
$session = curl_init($api_url . "/b2api/v1/b2_start_large_file");
curl_setopt($session, CURLOPT_HTTPHEADER, $headers);  // Add headers
curl_setopt($session, CURLOPT_POSTFIELDS, $post_fields); 
curl_setopt($session, CURLOPT_RETURNTRANSFER, true); // Receive server response
// Post the data
$server_output = curl_exec($session);
curl_close ($session);
print $server_output;

?>

Output

{
  "accountId": "YOUR_ACCOUNT_ID",
  "bucketId": "e73ede9c9c8412db49f60715",
  "contentType": "b2/x-auto",
  "fileId": "4_za71f544e781e6891531b001a_f200ec353a2184825_d20160409_m004829_c000_v0001016_t0028",
  "fileInfo": {},
  "fileName": "bigfile.dat",
  "uploadTimestamp": 1460162909000
}