b2_download_file_by_id

Downloads one file from B2.

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-dispostion)

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.

If the bucket containing the file is set to require authorization, then you must supply the account's auth token in the Authorization header.

Because errors can happen in network transmission, you should check the SHA1 of the data you receive against the SHA1 returned in the X-Bz-Content-Sha1 header.

Request

Request HTTP Headers

Authorization

optional

An account authorization token, obtained from b2_authorize_account. This is required if the bucket containing the file is not public. It is optional for buckets that are public.

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.

b2-content-disposition

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 (except that parameter names that contain an '*' are not allowed).
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.

The URL to use for downloading starts with the downloadUrl returned by b2_authorize_account, followed by /b2api/v1/b2_download_file_by_id, and looks like this: https://f001.backblazeb2.com/b2api/v1/b2_download_file_by_id.

As with normal API calls, the request information can either be posted as JSON, or put in the URL query parameters. Unlike the other API calls, the response is not JSON, but is the contents of the file.

Request HTTP Message Body Parameters

fileId

Required

The file ID that was returned from b2_upload_file. It can also be found using b2_list_files or b2_list_file_versions.

Example

GET /api/b2_download_file_by_id?fileId=4_h4a48fe8875c6214145260818_f000000000000472a_d20140104_m032022_c001_v0000123_t0104 HTTP/1.1
User-Agent: curl/7.41.0
Host: f001.backblazeb2.com
Authorization: 1_20100215141633_18d3a718d3a718d3a718d3a7_1d148b2427e9aff1364898aae20246802ec9733d

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 X-Bz-FileName 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

message

400

bad_request

No Authorization header

401

unauthorized

Not authorized

404

not_found

file_state_deleted

404

not_found

file_state_none

404

not_found

file_state_unknown

416

range_not_satisfiable

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

Sample Code

Code

DOWNLOAD_URL=...
FILE_ID=...

curl "$DOWNLOAD_URL/b2api/v1/b2_download_file_by_id?fileId=$FILE_ID"

Output

The quick brown fox jumped over the lazy dog.

Code

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

String downloadUrl = ""; // Provided by authorize account
String fileId = "";  // The file ID of the file you want to download
HttpURLConnection connection = null;
byte downloadedData[] = null;
try {
    URL url = new URL(downloadUrl + "/b2api/v1/b2_download_file_by_id?fileId=" + fileId);
    connection = (HttpURLConnection)url.openConnection();
    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 json
import urllib2

download_url = "" # Provided by authorize account
file_id = "" # The file ID of the file you want to download
print urllib2.urlopen(download_url + '/b2api/v1/b2_download_file_by_id?fileId=' + file_id)

Output

The quick brown fox jumped over the lazy dog.

Code

import Foundation

let downloadUrl = "" // Provided by b2_authorize_account
let fileId = "" // B2 file ID of the file you want to download
let session = NSURLSession.sharedSession()
if let urlComponents = NSURLComponents(string: "\(downloadUrl)/b2api/v1/b2_download_file_by_id") {
    urlComponents.query = "fileId=\(fileId)"
    let request = NSMutableURLRequest(URL: urlComponents.URL!)
    request.HTTPMethod = "GET"
    request.addValue(accountAuthorizationToken, forHTTPHeaderField: "Authorization")
    let task = session.dataTaskWithRequest(request, fromData: uploadData, completionHandler:{ (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
        if data != nil {
            // Do something with NSData
        }
    })
    task.resume()
}

Output

The quick brown fox jumped over the lazy dog.

Code

require 'json'
require 'net/http'

download_url = "" # Provided by authorize account
file_id = "" # The file ID of the file you want to download
uri = URI("#{download_url}/b2api/v1/b2_download_file_by_id?fileId=#{file_id}")
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

Output

The quick brown fox jumped over the lazy dog.

Code

string fileId = "FILE_ID" // The unique file ID
string downloadUrl = "DOWNLOAD_URL"; // Provided by b2_authorize_account
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(downloadUrl + "/b2api/v1/b2_download_file_by_id");
string body = "{\"fileId\":\"" + fileId + "\"}";
var data = Encoding.UTF8.GetBytes(body);
webRequest.Method = "POST";
webRequest.Headers.Add("Authorization", accountAuthorizationToken);
webRequest.ContentType = "application/json; charset=utf-8";
webRequest.ContentLength = data.Length;
using (var stream = webRequest.GetRequestStream())
{
	stream.Write(data, 0, data.Length);
	stream.Close();
}
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
$file_id = ""; // The ID of the file you want to download
$uri = $download_url . "/b2api/v1/b2_download_file_by_id?fileId=" . $file_id;

$session = curl_init($uri);

curl_setopt($session, CURLOPT_HTTPGET, true); // HTTP GET
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.