b2_copy_file

IN BETA - COMING SOON!

This API endpoint is in development. The API and this documentation is subject to change before this feature is released.

Creates a new file by copying from an existing file.

When calling b2_copy_file, by default the entire source file will be copied to the destination. If you wish, you may supply a range param to only copy a portion of the source file over.

Note that currently, we do not support cross-bucket copies. The source and destination file must be in the same bucket.

File Metadata

When copying files, you have the option to either copy the source file's metadata over to the new file, OR generate new metadata (but not both). Use the metadataDirective to indicate which strategy you wish to use.

  • COPY will set the new file's metadata to be equal to the source file's metadata.
  • REPLACE will ignore the source file's metadata, and set what you provide.

Note that a 400 will be returned in the following two scenarios:

  • The metadataDirective is COPY and contentType is set to a non-null value.
  • The metadataDirective is REPLACE and contentType is not set, or is null.

Request

The upload request is a POST.

Request HTTP Headers

Authorization

required

An account authorization token, obtained from b2_authorize_account. The token must have the writeFiles capability and the readFiles capability if the bucket is private.

Request HTTP Message Body Parameters

sourceFileId

required

The ID of the source file being copied.

fileName

required

The name of the new file being created.

range

optional

The range of bytes to copy. If not provided, the whole source file will be copied.

metadataDirective

optional

The strategy for how to populate metadata for the new file. If COPY is the indicated strategy, then supplying the contentType or fileInfo param is an error.

contentType

optional

Must only be supplied if the metadataDirective is REPLACE.
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

Must only be supplied if the metadataDirective is REPLACE.
This field stores the metadata that will be stored with the file. It follows the same rules that are applied to b2_upload_file

Response

Response HTTP Status 200

File successfully copied. The JSON response will contain the standard file information. For copied files, the action is always "copy".

accountId

The account that owns the file.

action

One of "start", "upload", "hide", "folder", or other values added in the future. "upload" means a file that was uploaded to B2 Cloud Storage. "start" means that a large file has been started, but not finished or canceled. "hide" means a file version marking the file as hidden, so that it will not show up in b2_list_file_names. "folder" is used to indicate a virtual folder when listing files.

bucketId

The bucket that the file is in.

contentLength

The number of bytes stored in the file. Only useful when the action is "upload". Always 0 when the action is "start", "hide", or "folder".

contentSha1

The SHA1 of the bytes stored in the file as a 40-digit hex string. Large files do not have SHA1 checksums, and the value is "none". The value is null when the action is "hide" or "folder".

contentType

When the action is "upload" or "start", the MIME type of the file, as specified when the file was uploaded. For "hide" action, always "application/x-bz-hide-marker". For "folder" action, always null.

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. The value is null when for action "folder".

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.

fileName

The name of this file, which can be used with b2_download_file_by_name.

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).
Always 0 when the action is "folder".

Response Errors

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

403

cap_exceeded

Usage cap exceeded.

404

not_found

File is not in B2 Cloud Storage.

405

method_not_allowed

Only POST is supported

408

request_timeout

The service timed out reading the uploaded file

416

range_not_satisfiable

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

Sample Code

Code

ACCOUNT_AUTHORIZATION_TOKEN=''; # Provided by b2_authorize_account
API_URL=''; # Provided by b2_authorize_account
SOURCE_FILE_ID=''; # The file you wish to copy
FILE_NAME='test-b2-copy-file-curl'; # The name of the new file
curl \
    -H "Authorization: $ACCOUNT_AUTHORIZATION_TOKEN" \
    -d "`printf '{"sourceFileId":"%s", "fileName":"%s", "range":"bytes=1000-2000"}' $SOURCE_FILE_ID $FILE_NAME`" \
    "$API_URL/b2api/v2/b2_copy_file";

Output

{
  "accountId": "YOUR_ACCOUNT_ID",
  "action": "copy",
  "bucketId": "BUCKET_ID",
  "contentLength": 1001,
  "contentSha1": "300efddb6be85bfe74f76a89ad4ef94fcf9a0b7b",
  "contentType": "video/quicktime",
  "fileId": "NEW_FILE_ID",
  "fileInfo": {
    "src_last_modified_millis": "1554914807970"
  },
  "fileName": "test-b2-copy-file-curl",
  "uploadTimestamp": 1559580871000
}

Code

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class B2CopyFile {

    public static void main(String[] args) throws IOException {
        final String apiUrl = ""; // Provided by b2_authorize_account
        final String accountAuthorizationToken = ""; // Provided by b2_authorize_account
        final String sourceFileId = ""; // The file you wish to copy
        final String fileName = "test-b2-copy-file-java";

        final URL url = new URL(apiUrl + "/b2api/v2/b2_copy_file");
        final HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        try {
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Authorization", accountAuthorizationToken);

            connection.setDoOutput(true);
            DataOutputStream writer = new DataOutputStream(connection.getOutputStream());
            writer.write((
                    "{"
                            + "\"sourceFileId\": \"" + sourceFileId + "\","
                            + "\"fileName\": \"" + fileName + "\""
                            + "}").getBytes(StandardCharsets.UTF_8)
            );
            final InputStream in = new BufferedInputStream(connection.getInputStream());
            final String jsonResponse = inputStreamToString(in);

            System.out.println(jsonResponse);
        } finally {
            connection.disconnect();
        }
    }

    private static String inputStreamToString(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",
  "action": "copy",
  "bucketId": "BUCKET_ID",
  "contentLength": 99212871,
  "contentSha1": "c604542967a93466d4ed087956753161cfab3f31",
  "contentType": "video/quicktime",
  "fileId": "NEW_FILE_ID",
  "fileInfo": {
    "src_last_modified_millis": "1554914807970"
  },
  "fileName": "test-b2-copy-file-java",
  "uploadTimestamp": 1559584405000
}

Code

import json
import urllib2

api_url = '' # Provided by b2_authorize_account
account_authorization_token = '' # Provided by b2_authorize_account
source_file_id = '' # The file you wish to copy
file_name = 'test-b2-copy-file-python'
request = urllib2.Request(
    '%s/b2api/v2/b2_copy_file' % api_url,
    json.dumps({
      'sourceFileId' : source_file_id,
      'fileName': file_name,
    }),
    headers = {
        'Authorization': account_authorization_token
    })
response = urllib2.urlopen(request)
response_data = json.loads(response.read())
print(json.dumps(response_data, indent=2))
response.close()

Output

{
  "contentType": "video/quicktime",
  "contentSha1": "c604542967a93466d4ed087956753161cfab3f31",
  "bucketId": "BUCKET_ID",
  "contentLength": 99212871,
  "fileName": "test-b2-copy-file-python",
  "action": "copy",
  "fileInfo": {
    "src_last_modified_millis": "1554914807970"
  },
  "fileId": "NEW_FILE_ID",
  "uploadTimestamp": 1559585435000,
  "accountId": "YOUR_ACCOUNT_ID"
}

Code

under construction

Output

under construction

Code

under construction

Output

under construction

Code

under construction

Output

under construction

Code

under construction

Output

under construction