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-disposition)
The response also includes a header with the timestamp from when the upload began:
- X-Bz-Upload-Timestamp
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.
- Content-Language : computed from the b2-content-language provided when the file was uploaded or specified during the download request.
- Expires : computed from the b2-expires provided when the file was uploaded or specified during the download request.
- Cache-Control : computed from the download request, otherwise the value provided when the file was uploaded, otherwise the value specified on the bucket.
- Content-Encoding : computed from the b2-content-encoding provided when the file was uploaded or specified during the download request.
- X-Bz-Server-Side-Encryption : if the file was encrypted with SSE-B2, then the value is the algorithm used for encryption; otherwise omitted.
- X-Bz-Server-Side-Encryption-Customer-Algorithm : if the file was encrypted with SSE-C, then the value is the algorithm used for encryption; otherwise omitted.
- X-Bz-Server-Side-Encryption-Customer-Key-Md5 : if the file was encrypted with SSE-C, then the value is the MD5 digest of the customer-managed encryption key used for encryption, otherwise omitted.
If the file is in a bucket that is Object Lock-enabled, then the following headers may also be present:
- X-Bz-File-Retention-Mode : if Object Lock retention settings are
enabled for the file and the client has the
readFileRetentions
application key capability, then the value is the file retention mode (governance
orcompliance
). - X-Bz-File-Retention-Retain-Until-Timestamp : if Object Lock retention
settings are enabled for the file and the client has the
readFileRetentions
application key capability, then the value is the file retention timestamp, specified as a base 10 number of milliseconds since midnight, January 1, 1970 UTC. - X-Bz-File-Legal-Hold : if Object Lock legal hold has been enabled or
disabled for the file and the client has the
readFileLegalHolds
application key capability, then the value is the current status (on
oroff
). - X-Bz-Client-Unauthorized-To-Read : if the client does not have
readFileRetentions
and/orreadFileLegalHolds
application key capabilities, then the value will include names of headers which are not present because the client does not have appropriate permissions to access those values (e.g.,X-Bz-File-Retention-Mode,X-Bz-File-Retention-Retain-Until-Timestamp
).
When only the header information is required, use the more efficient
HEAD
request rather than requesting a single byte
of the file.
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 Details
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.
This must be in the request's headers.
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 partial byte ranges will cause the response
to contain a Content-Range header that specifies which
bytes are returned. Invalid byte ranges or a byte range
that encloses the entire stored file's content 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 part of the
stored file is returned. The status code for the response
is 200 OK (and no Content-Range header is included) when
the whole file is returned.
This must be in the request's headers.
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 exceeds the
7000-byte overall limit (2048 bytes for files encrypted
with SSE), this request will be rejected. See
Files
for further details about HTTP header size limit.
Requests with this specified must also have an authorization
token.
This may be in the URL's query parameters or in the POSTed JSON request.
b2ContentLanguage
optional
If this is present, B2 will use it as the
value of the 'Content-Language' header, overriding any
'b2-content-language' specified when the file was uploaded.
The value must match the grammar specified in RFC 2616.
Note that this file info will not be
included in downloads as a x-bz-info-b2-content-language
header. Instead, it (or the value specified in a request) will
be in the Content-Language.
If including this header in the response exceeds the
7000-byte overall limit (2048 bytes for files encrypted
with SSE), this request will be rejected. See
Files
for further details about HTTP header size limit.
Requests with this specified must also have an authorization
token.
This may be in the URL's query parameters or in the POSTed JSON request.
b2Expires
optional
If this is present, B2 will use it as the
value of the 'Expires' header, overriding any
'b2-expires' specified when the file was uploaded.
The value must match the grammar specified in RFC 2616.
Note that this file info will not be
included in downloads as a x-bz-info-b2-expires
header. Instead, it (or the value specified in a request) will
be in the Expires.
If including this header in the response exceeds the
7000-byte overall limit (2048 bytes for files encrypted
with SSE or in Object Lock-enabled buckets), this request
will be rejected.
See Files for
further details about HTTP header size limit.
Requests with this specified must also have an authorization
token.
This may be in the URL's query parameters or in the POSTed JSON request.
b2CacheControl
optional
If this is present, B2 will use it as the
value of the 'Cache-Control' header, overriding any
'b2-cache-control' specified when the file was uploaded.
The value must match the grammar specified in RFC 2616.
Note that this file info will not be
included in downloads as a x-bz-info-b2-cache-control
header. Instead, it (or the value specified in a request) will
be in the Cache-Control.
If including this header in the response exceeds the
7000-byte overall limit (2048 bytes for files encrypted
with SSE), this request will be rejected. See
Files
for further details about HTTP header size limit.
Requests with this specified must also have an authorization
token.
This may be in the URL's query parameters or in the POSTed JSON request.
b2ContentEncoding
optional
If this is present, B2 will use it as the
value of the 'Content-Encoding' header, overriding any
'b2-content-encoding' specified when the file was uploaded.
The value must match the grammar specified in RFC 2616.
Note that this file info will not be
included in downloads as a x-bz-info-b2-content-encoding
header. Instead, it (or the value specified in a request) will
be in the Content-Encoding.
If including this header in the response exceeds the
7000-byte overall limit (2048 bytes for files encrypted
with SSE), this request will be rejected. See
Files
for further details about HTTP header size limit.
Requests with this specified must also have an authorization
token.
This may be in the URL's query parameters or in the POSTed JSON request.
b2ContentType
optional
If this is present, B2 will use it as the
value of the 'Content-Type' header, overriding any
'Content-Type' specified when the file was uploaded.
The value must match the grammar specified in RFC 2616.
Note that this file info will not be
included in downloads as a x-bz-info-b2-content-type
header. Instead, it (or the value specified in a request) will
be in the Content-Type.
If including this header in the response exceeds the
7000-byte overall limit (2048 bytes for files encrypted
with SSE), this request will be rejected. See
Files
for further details about HTTP header size limit.
Requests with this specified must also have an authorization
token.
This may be in the URL's query parameters or in the POSTed JSON request.
serverSideEncryption
optional
This parameter is required if the file was uploaded and
stored
using Server-Side
Encryption with Customer-Managed Keys (SSE-C). In that
case, this parameter is used to specify the mode, algorithm,
customer-managed encryption key, and MD5 digest of that key
that were provided at upload time.
The necessary parameters may also be specified in the
request headers using the
X-Bz-Server-Side-Encryption-Customer-Algorithm
,
X-Bz-Server-Side-Encryption-Customer-Key
, and
X-Bz-Server-Side-Encryption-Customer-Key-Md5
headers.
The URL to use for downloading starts with the downloadUrl
returned by b2_authorize_account
, followed by
/b2api/v2/b2_download_file_by_id
, and looks like this:
https://f001.backblazeb2.com/b2api/v2/b2_download_file_by_id
.
As with normal API calls, most of the request information can either be posted as JSON, or put in the URL query parameters. See above for details. 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 |
description |
---|---|---|
400 |
bad_bucket_id |
The requested bucket ID does not match an existing bucket. |
400 |
bad_request |
The request had the wrong fields or illegal values. The message returned with the error will describe the problem. |
400 |
cannot_delete_non_empty_bucket |
A bucket must be empty before it can be deleted. To delete this bucket, first remove all of the files in the bucket, then try the delete operation again. |
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. |
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. |
403 |
access_denied |
The provided customer-managed encryption key is wrong. |
403 |
download_cap_exceeded |
Usage cap exceeded. |
403 |
transaction_cap_exceeded |
Transaction cap exceeded. To increase your cap, sign in to your B2 Cloud Storage account online. Then select the Caps & Alerts link in the B2 Cloud Storage section of the sidebar. |
404 |
not_found |
File is not in B2 Cloud Storage. |
416 |
range_not_satisfiable |
The Range header in the request is valid but cannot be satisfied for 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=...
FILE_ID=...
curl "$DOWNLOAD_URL/b2api/v2/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/v2/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/v2/b2_download_file_by_id?fileId=' + file_id)
Output
The quick brown fox jumped over the lazy dog.
Code
import Foundation
let accountAuthorizationToken = "" // Provided by b2_authorize_account
let downloadUrl = "" // Provided by b2_authorize_account
let fileId = "" // B2 file ID of the file you want to download
// Create the URL
var urlComponents = URLComponents(string: "\(downloadUrl)/b2api/v2/b2_download_file_by_id")!
urlComponents.query = "fileId=\(fileId)"
// Create the request
var request = URLRequest(url: urlComponents.url!)
request.httpMethod = "GET"
request.addValue(accountAuthorizationToken, forHTTPHeaderField: "Authorization")
// 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
file_id = "" # The file ID of the file you want to download
uri = URI("#{download_url}/b2api/v2/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/v2/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/v2/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.