b2_download_file_by_name

Downloads one file by providing the name of the bucket and the name of the file.

The base URL to use comes from the b2_authorize_account call, and looks something like https://f345.backblazeb2.com. The "f" in the URL stands for "file", and the number is the cluster number containing your account. To this base, you add "file/", your bucket name, a "/", and then the name of the file. The file name may itself include more "/" characters.

In case where only the headers are required, the more efficient HEAD request provides a more efficient means of retrieving them.

If you have a bucket named "photos", and a file called "cute/kitten.jpg", then the URL for downloading that file would be: https://f345.backblazeb2.com/file/photos/cute/kitten.jpg.

The response contains the following headers, which contain the same information they did when the file was uploaded.

  • Content-Length
  • Content-Type
  • X-Bz-File-Id
  • X-Bz-File-Name
  • X-Bz-Content-Sha1
  • X-Bz-Info-* (except for the ones that set other response headers, such as b2-content-disposition)

The response also includes a header with the timestamp from when the upload began:

  • X-Bz-Upload-Timestamp
  • Cache-Control : max-age (only); inherited from Bucket Info.
The following headers may be present:
  • Content-Disposition : computed from the b2-content-disposition provided when the file was uploaded or specified during the download request.

Request

Request HTTP Headers

Authorization

optional

An account authorization token, obtained from b2_authorize_account. The token must have the readFiles capability.
This is required if the bucket containing the file is not public. It is optional for buckets that are public.
Alternatively, a download authorization token obtained from b2_get_download_authorization can be used to access files whose names begin with the filename prefix that was used to generate the download authorization token.

Range

optional

A standard byte-range request, which will return just part of the stored file.
The value "bytes=0-99" selects bytes 0 through 99 (inclusive) of the file, so it will return the first 100 bytes. Valid byte ranges will cause the response to contain a Content-Range header that specifies which bytes are returned. Invalid byte ranges will just return the whole file.
Note that the SHA1 checksum returned is still the checksum for the entire file, so it cannot be used on the byte range.
The status code for a successful response to a Range request is 206 Partial Content.
When only the header information is required, the HEAD request provides a more efficient means of retrieving the headers than requesting the first few bytes of the file.

Request HTTP Message Body Parameters

This is a GET request, so you cannot post any parameters. You may pass arguments in the URL query string.

Request HTTP URL Parameters

Authorization

optional

An authorization token can be provided in the URL query string instead of being passed in the HTTP header. An account authorization token obtained from b2_authorize_account will allow access to all files in a private bucket. A download authorization token obtained from b2_get_download_authorization will allow access to files whose names begin with the filename prefix used to generate the download authorization token. For example:

https://f345.backblazeb2.com/file/photos/cute/kitten.jpg?Authorization=3_20160803004041_53982a92f631a8c7303e3266_d940c7f5ee17cd1de3758aaacf1024188bc0cd0b_000_20160804004041_0006_dnld

b2ContentDisposition

optional

If this is present, B2 will use it as the value of the 'Content-Disposition' header, overriding any 'b2-content-disposition' specified when the file was uploaded.
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.
If including this header in the response exceed the 7000-byte overall limit, this request will be rejected.
Requests with this specified must also have an authorization token. If the token was generated with b2_get_download_authorization, this b2-content-disposition must have the same value that was provided to b2_get_download_authorization.

Response

Response HTTP Status 200

The response headers include the Content-Type that was specified when the file was uploaded. They also include the X-Bz-FileName and X-Bz-Content-Sha1 headers, plus X-Bz-Info-* headers for any custom file info that was provided with the upload. The file-name uses percent-encoding, as if it were a URL parameter.

Example

HTTP/1.1 200 OK
Content-Length: 46
Content-Type: text/plain
X-Bz-File-Id: 4_h4a48fe8875c6214145260818_f000000000000472a_d20140104_m032022_c001_v0000123_t0104
X-Bz-File-Name: typing-test.txt
X-Bz-Content-Sha1: bae5ed658ab3546aee12f23f36392f35dba1ebdd
X-Bz-Info-author: unknown

The quick brown fox jumped over the lazy dog.

Response Errors

File not returned. 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.

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.

404

not_found

File is not in B2 Cloud Storage.

416

range_not_satisfiable

The Range header in the request is outside the size of the file.

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

DOWNLOAD_URL=... # Comes from b2_authorize_account
BUCKET_NAME=... # The name of your bucket (not the ID)
FILE_NAME=... # The name of the file in the bucket

curl ${DOWNLOAD_URL}/file/${BUCKET_NAME}/${FILE}

# You will need to use the account authorization token if your bucket's type is allPrivate.

DOWNLOAD_URL=... # Comes from b2_authorize_account
BUCKET_NAME=... # The name of your bucket (not the ID)
FILE_NAME=... # The name of the file in the bucket
ACCOUNT_AUTHORIZATION_TOKEN=... # Comes from the b2_authorize_account call

curl -H "Authorization: $ACCOUNT_AUTHORIZATION_TOKEN" \
    "${DOWNLOAD_URL}/file/${BUCKET_NAME}/${FILE}"

Output

The quick brown fox jumped over the lazy dog.

Code

String downloadUrl = ""; // Provided by b2_authorize_account
String bucketName = ""; // The bucket name where the file exists
String fileName = ""; // The file name of the file you want to download.
HttpURLConnection connection = null;
byte downloadedData[] = null;
try {
    URL url = new URL(downloadUrl + "/file/" + bucketName + "/" + fileName);
    connection = (HttpURLConnection)url.openConnection();
    connection.setRequestMethod("GET");
    connection.setDoOutput(true);
    downloadedData = myDataInputStreamHandler(connection.getInputStream());
} catch (Exception e) {
    e.printStackTrace();
} finally {
    connection.disconnect();
}

// You will need to use the account authorization token if your bucket's type is allPrivate.

String accountAuthorizationToken = "";  // Provided by b2_authorize_account
String downloadUrl = ""; // Provided by b2_authorize_account
String bucketName = ""; // The bucket ID where the file exists
String fileName = ""; // The file name of the file you want to download.
HttpURLConnection connection = null;
byte downloadedData[] = null;
try {
    URL url = new URL(downloadUrl + "/file/" + bucketName + "/" + fileName);
    connection = (HttpURLConnection)url.openConnection();
    connection.setRequestProperty("Authorization", accountAuthorizationToken);
    connection.setRequestMethod("GET");
    connection.setDoOutput(true);
    downloadedData = myDataInputStreamHandler(connection.getInputStream());
} catch (Exception e) {
    e.printStackTrace();
} finally {
    connection.disconnect();
}

Output

The quick brown fox jumped over the lazy dog.

Code

import urllib2

DOWNLOAD_URL = "..." # Comes from b2_authorize_account
BUCKET_NAME = "..." # The name of your bucket (not the ID)
FILE_NAME = "..." # The name of the file in the bucket

url = DOWNLOAD_URL + '/file/' + BUCKET_NAME + '/' + FILE_NAME
print urllib2.urlopen(url).read()

# You will need to use the account authorization token if your bucket's type is allPrivate.

DOWNLOAD_URL = "..." # Comes from b2_authorize_account
BUCKET_NAME = "any_name_you_pick" # 50 char max: letters, digits, “-“ and “_” 
FILE_NAME = "..." # The name of the file in the bucket
ACCOUNT_AUTHORIZATION_TOKEN = "..." # Comes from the b2_authorize_account call

url = DOWNLOAD_URL + '/file/' + BUCKET_NAME + '/' + FILE_NAME

headers = {
    'Authorization': ACCOUNT_AUTHORIZATION_TOKEN
    }

request = urllib2.Request(url, None, headers)
response = urllib2.urlopen(request)
response_data = json.loads(response.read())
response.close()

Output

The quick brown fox jumped over the lazy dog.

Code

import Foundation

// Suitable for when a bucketType is set to allPublic.

let downloadUrl = "" // Provided by b2_authorize_account
let bucketName = "" // The bucket name where the file exists
let fileName = "" // The file name of the file you want to download. See 
                  // b2_download_file_by_name documentation for more information how the 
                  // fileName should be constructed.

// Create the request
var request = URLRequest(url: URL(string: "\(downloadUrl)/file/\(bucketName)/\(fileName)")!)
request.httpMethod = "GET"

// Create the task
let task = URLSession.shared.downloadTask(with: request) { (url, urlResponse, error) in
	// Assuming the download was successful
	print("MyDownloadedFile:\((url?.path)!)")
}

// Start the task
task.resume()

// Suitable for when a bucketType is set to allPrivate.
// You will need to use the account authorization token if your bucket's type is allPrivate.

let accountAuthorizationToken = "" // Provided by b2_authorize_account or b2_get_download_authorization. See documentation for clarification
let downloadUrl = "" // Provided by b2_authorize_account
let bucketName = "" // The bucket name where the file exists
let fileName = "" // The file name of the file you want to download

// Create the request
var request = URLRequest(url: URL(string: "\(downloadUrl)/file/\(bucketName)/\(fileName)")!)
request.httpMethod = "GET"
request.addValue(accountAuthorizationToken, forHTTPHeaderField: "Authorization") // optional

// Create the task
let task = URLSession.shared.downloadTask(with: request) { (url, urlResponse, error) in
	// Assuming the download was successful
	print("MyDownloadedFile:\((url?.path)!)")
}

// Start the task
task.resume()

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

Output

The quick brown fox jumped over the lazy dog.

Code

require 'json'
require 'net/http'

download_url = "" # Provided by authorize account
bucket_name = "" # The NAME of the bucket you want to download from
file_name = "" # The file name of the file you want to download
uri = URI("#{download_url}/file/#{bucket_name}/#{file_name}")
req = Net::HTTP::Get.new(uri)
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

# You will need to use the account authorization token if your bucket's type is allPrivate.

download_url = "" # Provided by authorize account
bucket_name = "" # The NAME of the bucket you want to download from
file_name = "" # The file name of the file you want to download
account_authorization_token = "" # B2 Cloud Authorization Token
uri = URI("#{download_url}/file/#{bucket_name}/#{file_name}")
req = Net::HTTP::Get.new(uri)
req.add_field("Authorization","#{account_authorization_token}")
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

The quick brown fox jumped over the lazy dog.

Code

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

string downloadUrl = ""; // Provided by b2_authorize_account
string bucketName = ""; // The bucket name where the file exists
string fileName = ""; // The file ID of the file you want to download
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(String.Format("{0}/file/{1}/{2}", downloadUrl, bucketName, fileName));
webRequest.Method = "GET";
WebResponse response = (HttpWebResponse)webRequest.GetResponse();
Stream responseStream = response.GetResponseStream();
byte[] fileBytes;
using (BinaryReader br = new BinaryReader(responseStream))
{
    fileBytes = br.ReadBytes(500000);
    br.Close();
}
responseStream.Close();
response.Close();
string downloadsFolder = @"FILE DIRECTORY HERE";
FileStream saveFile = new FileStream(downloadsFolder, FileMode.Create);
BinaryWriter writeFile = new BinaryWriter(saveFile);
try
{
    writeFile.Write(fileBytes);
}
finally
{
    saveFile.Close();
    writeFile.Close();
}

// You will need to use the account authorization token if your bucket's type is allPrivate.

string downloadUrl = ""; // Provided by b2_authorize_account
string bucketName = ""; // The bucket name where the file exists
string fileName = ""; // The file ID of the file you want to download
string accountAuthorizationToken = "ACCOUNT_AUTHORIZATION_TOKEN"; //Provided by b2_authorize_account
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(String.Format("{0}/file/{1}/{2}", downloadUrl, bucketName, fileName)); 
webRequest.Method = "GET";
webRequest.Headers.Add("Authorization", accountAuthorizationToken);
WebResponse response = (HttpWebResponse)webRequest.GetResponse();
Stream responseStream = response.GetResponseStream();
byte[] fileBytes;
using (BinaryReader br = new BinaryReader(responseStream))
{
    fileBytes = br.ReadBytes(500000);
    br.Close();
}
responseStream.Close();
response.Close();
string downloadsFolder = @"FILE DIRECTORY HERE";
FileStream saveFile = new FileStream(downloadsFolder, FileMode.Create);
BinaryWriter writeFile = new BinaryWriter(saveFile);
try
{
    writeFile.Write(fileBytes);
}
finally
{
    saveFile.Close();
    writeFile.Close();
}

Output

The quick brown fox jumped over the lazy dog.

Code

$download_url = ""; // From b2_authorize_account call
$bucket_name = "";  // The NAME of the bucket you want to download from
$file_name = "file.txt"; // The name of the file you want to download
$uri = $download_url . "/file/" . $bucket_name . "/" . $file_name;

$session = curl_init($uri);

curl_setopt($session, CURLOPT_HTTPGET, true); // HTTP GET
curl_setopt($session, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);  // Receive server response
$server_output = curl_exec($session); // Let's do this!
curl_close ($session); // Clean up
echo ($server_output); // Tell me about the rabbits, George!

// You will need to use the account authorization token if your bucket's type is allPrivate.

$download_url = ""; // From b2_authorize_account call
$bucket_name = "";  // The NAME of the bucket you want to download from
$file_name = "file.txt"; // The name of the file you want to download
$auth_token = ""; // From b2_authorize_account call
$uri = $download_url . "/file/" . $bucket_name . "/" . $file_name;

$session = curl_init($uri);

// Add headers
$headers = array();
$headers[] = "Authorization: " . $auth_token;
curl_setopt($session, CURLOPT_HTTPHEADER, $headers); 

curl_setopt($session, CURLOPT_HTTPGET, true); // HTTP POST
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);  // Receive server response
$server_output = curl_exec($session); // Let's do this!
curl_close ($session); // Clean up
echo ($server_output); // Tell me about the rabbits, George!

Output

The quick brown fox jumped over the lazy dog.