Data Types

Bytescale JavaScript SDK

Lightweight headless SDK for uploading, processing, and hosting files with Bytescale.

Install

To install via NPM:

npm install @bytescale/sdk

To install via a script tag:

<script src="https://js.bytescale.com/sdk/v3"></script>

Upload a File Basic Example

To upload a file with the Bytescale JavaScript SDK (basic example):

1<html>
2 <head>
3 <script src="https://js.bytescale.com/sdk/v3"></script>
4 <script>
5 // import * as Bytescale from "@bytescale/sdk";
6 const uploadManager = new Bytescale.UploadManager({
7 apiKey: "free" // Get API key: https://www.bytescale.com/get-started
8 });
9
10 const onFileSelected = async event => {
11 const file = event.target.files[0];
12
13 try {
14 // The 'data' field supports:
15 // - String
16 // - Blob
17 // - ArrayBuffer
18 // - File (i.e. from a DOM file input element)
19 const { fileUrl, filePath } = await uploadManager.upload({ data: file });
20
21 // --------------------------------------------
22 // File successfully uploaded!
23 // --------------------------------------------
24 // The 'filePath' uniquely identifies the file,
25 // and is what you should save to your API.
26 // --------------------------------------------
27 alert(`File uploaded:\n${fileUrl}`);
28
29 } catch (e: any) {
30 alert(`Error:\n${e.message}`);
31 }
32 }
33 </script>
34 </head>
35 <body>
36 <input type="file" onchange="onFileSelected(event)" />
37 </body>
38</html>

See also: UploadManagerParams

Upload a File Advanced Example

To upload a file with the Bytescale JavaScript SDK (advanced example):

1<html>
2 <head>
3 <script src="https://js.bytescale.com/sdk/v3"></script>
4 <script>
5 // import * as Bytescale from "@bytescale/sdk";
6 const uploadManager = new Bytescale.UploadManager({
7 apiKey: "free" // Get API key: https://www.bytescale.com/get-started
8 });
9
10 const onFileSelected = async event => {
11 const file = event.target.files[0];
12
13 try {
14 const { fileUrl, filePath } = await uploadManager.upload({
15
16 // Supported types:
17 // - String
18 // - Blob
19 // - ArrayBuffer
20 // - File (i.e. from a DOM file input element)
21 data: file,
22
23 // ---------
24 // Optional:
25 // ---------
26
27 // Required if 'data' is a stream. Node.js only. (Not required when uploading files from the browser.)
28 // size: 5098, // e.g. fs.statSync("file.txt").size
29
30 // Required if 'data' is a stream, buffer, or string. (Not required for DOM file inputs or blobs.)
31 // mime: "application/octet-stream",
32
33 // Required if 'data' is a stream, buffer, or string. (Not required for DOM file inputs or blobs.)
34 // originalFileName: "my_file.txt",
35
36 // Reports progress: bytesTotal, bytesSent, progress.
37 // onProgress: ({ progress }) => console.log(progress),
38
39 // Controls multipart upload concurrency. Ignored if 'data' is a stream.
40 // maxConcurrentUploadParts: 4,
41
42 // Up to 2KB of arbitrary JSON.
43 // metadata: {
44 // productId: 60891
45 // },
46
47 // Up to 25 tags per file.
48 // tags: [
49 // "example_tag"
50 // ],
51
52 // About file paths:
53 // - Your API key's "file upload path" is used by default, and can be changed by editing the API key's settings.
54 // - You can override the API key's file upload path by specifying a path below.
55 // - You may use path variables (e.g. "{UTC_DAY}"): https://www.bytescale.com/docs/path-variables
56 // path: {
57 // folderPath: "/uploads/{UTC_YEAR}/{UTC_MONTH}/{UTC_DAY}",
58 // fileName: "{UTC_TIME_TOKEN_INVERSE}{UNIQUE_DIGITS_2}{ORIGINAL_FILE_EXT}"
59 // },
60
61 // Set to 'isCancelled = true' after invoking 'upload' to cancel the upload.
62 // cancellationToken: {
63 // isCancelled: false
64 // }
65 });
66
67 // --------------------------------------------
68 // File successfully uploaded!
69 // --------------------------------------------
70 // The 'filePath' uniquely identifies the file,
71 // and is what you should save to your API.
72 // --------------------------------------------
73 alert(`File uploaded:\n${fileUrl}`);
74
75 } catch (e: any) {
76 alert(`Error:\n${e.message}`);
77 }
78 }
79 </script>
80 </head>
81 <body>
82 <input type="file" onchange="onFileSelected(event)" />
83 </body>
84</html>

See also: UploadManagerParams and Path Variables

Live example:

Download a File

To download a file from your Bytescale account:

1import * as Bytescale from "@bytescale/sdk";
2
3const fileApi = new Bytescale.FileApi({
4 apiKey: "YOUR_API_KEY" // e.g. "public_xxxxx"
5});
6
7fileApi
8 .downloadFile({
9 accountId: "YOUR_ACCOUNT_ID", // e.g. "W142hJk"
10 filePath: "/uploads/2022/12/25/hello_world.txt"
11 })
12 .then(response => response.text()) // .text() | .json() | .blob() | .stream()
13 .then(
14 fileContents => console.log(fileContents),
15 error => console.error(error)
16 );

To learn more about these parameters, see the DownloadFile operation »

To get a file's URL (instead of downloading the file as a binary stream) use the UrlBuilder »

Delete a File

To delete an uploaded file:

1import * as Bytescale from "@bytescale/sdk";
2
3const fileApi = new Bytescale.FileApi({
4 apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
5});
6
7fileApi
8 .deleteFile({
9 accountId: "YOUR_ACCOUNT_ID", // e.g. "W142hJk"
10 filePath: "/uploads/2022/12/25/image.jpg"
11 })
12 .then(
13 () => console.log("File deleted."),
14 error => console.error(error)
15 );

There are no additional parameters to pass to the DeleteFile operation.

List Files

To list the children of a folder:

1import * as Bytescale from "@bytescale/sdk";
2
3const folderApi = new Bytescale.FolderApi({
4 apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
5});
6
7folderApi
8 .listFolder({
9 accountId: "YOUR_ACCOUNT_ID", // e.g. "W142hJk"
10 folderPath: "/",
11 recursive: false
12 })
13 .then(
14 // Note: operation is paginated, see 'result.cursor' and 'params.cursor'.
15 result => console.log(`Items in folder: ${result.items.length}`),
16 error => console.error(error)
17 );

To learn more about these parameters, see the ListFolder operation »

Get File Metadata

To get the full details of a file (including any custom metadata):

1import * as Bytescale from "@bytescale/sdk";
2
3const fileApi = new Bytescale.FileApi({
4 apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
5});
6
7fileApi
8 .getFileDetails({
9 accountId: "YOUR_ACCOUNT_ID", // e.g. "W142hJk"
10 filePath: "/uploads/2022/12/25/image.jpg"
11 })
12 .then(
13 fileDetails => console.log(fileDetails), // includes: size, mime, metadata, etc.
14 error => console.error(error)
15 );

There are no additional parameters to pass to the GetFileDetails operation.

Transforming Files

You can transform uploaded files using Bytescale's File Processing APIs:

To transform files with code and receive the result as a binary stream in JavaScript, use the processFile method:

1import * as Bytescale from "@bytescale/sdk";
2
3const fileApi = new Bytescale.FileApi({
4 apiKey: "YOUR_API_KEY" // e.g. "public_xxxxx"
5});
6
7fileApi
8 .processFile({
9 accountId: "YOUR_ACCOUNT_ID", // e.g. "W142hJk"
10 filePath: "/uploads/2022/12/25/image.jpg",
11
12 // Transformation Presets vs File Processing APIs:
13 // - To use a preset:
14 // - Specify the preset name below (e.g. "thumbnail").
15 // - Exclude the "transformationParams" field.
16 // - Presets are created in the Bytescale Dashboard.
17 // - To use a File Processing API:
18 // - Specify the File Processing API below (e.g. "image", "video", "audio", etc).
19 // - Include the "transformationParams" field.
20 // - Parameters are documented here: https://www.bytescale.com/docs/file-processing-apis
21 transformation: "image",
22
23 // Array Support:
24 // - Certain File Processing APIs, such as the Archive Processing API, have transformation
25 // parameters that can be specified multiple times (e.g. the "file" parameter).
26 // - To do this, use multiple objects to specify the same parameter name multiple times.
27 transformationParams: [
28 {
29 w: 800,
30 h: 600,
31 fit: "crop"
32 }
33 ]
34 })
35 .then(response => response.blob()) // .text() | .json() | .blob() | .stream()
36 .then(
37 imageBlob => {
38 const img = new Image();
39 img.src = URL.createObjectURL(imageBlob);
40 document.body.appendChild(img);
41 }
42 )
43 .then(
44 () => console.log("Thumbnail image inserted into DOM."),
45 error => console.error(error)
46 );

To transform files via the URL, use the UrlBuilder to construct file transformation URLs (see below).

File transformation URLs can be used in your webpages, e.g. in the src attribute of <img> and <video> elements.

Building URLs

After uploading a file, you should save its filePath to your DB instead of its fileUrl, and use the UrlBuilder to lazily create URLs:

  • filePath values are shorter.

  • filePath values allow you to change the domain in the future (e.g. if you move to a custom CNAME).

  • filePath values allow you to select different file transformations at runtime (e.g. /raw/, /image/, etc.).

You can use the UrlBuilder to create URLs from filePath values:

Raw Files

Using the UrlBuilder to get raw file URLs (i.e. URLs to original files):

// import * as Bytescale from "@bytescale/sdk";
// Returns: "https://upcdn.io/1234abc/raw/example.jpg"
Bytescale.UrlBuilder.url({
accountId: "1234abc",
filePath: "/example.jpg"
});

You can upload any file type to Bytescale. Use /raw/ when downloading files that don't need to be transformed.

Transformation Presets

Using the UrlBuilder to transform files using transformation presets:

// import * as Bytescale from "@bytescale/sdk";
// Returns: "https://upcdn.io/1234abc/thumbnail/example.jpg"
Bytescale.UrlBuilder.url({
accountId: "1234abc",
filePath: "/example.jpg",
options: {
transformation: "preset",
transformationPreset: "thumbnail"
}
});

Transformation presets are created in the Bytescale Dashboard.

Images

Using the UrlBuilder to transform images using the Image Processing API:

// import * as Bytescale from "@bytescale/sdk";
// Process images with:
// ↪ https://upcdn.io/abc1234/image/example.jpg?w=800&h=600
Bytescale.UrlBuilder.url({
accountId: "abc1234",
filePath: "/example.jpg",
options: {
transformation: "image",
transformationParams: {
"w": 800,
"h": 600
}
}
});

See the Image Processing API for the full list of transformationParams when transformation: "image".

Videos

Using the UrlBuilder to transform videos using the Video Processing API:

// import * as Bytescale from "@bytescale/sdk";
// Process videos with:
// ↪ https://upcdn.io/abc1234/video/example.mov?f=mp4-h264&h=1080
Bytescale.UrlBuilder.url({
accountId: "abc1234",
filePath: "/example.mov",
options: {
transformation: "video",
transformationParams: {
"f": "mp4-h264",
"h": 1080
}
}
});

See the Video Processing API for the full list of transformationParams when transformation: "video".

Audio

Using the UrlBuilder to transform audio using the Audio Processing API:

// import * as Bytescale from "@bytescale/sdk";
// Process audio with:
// ↪ https://upcdn.io/abc1234/audio/example.wav?f=aac&br=192
Bytescale.UrlBuilder.url({
accountId: "abc1234",
filePath: "/example.wav",
options: {
transformation: "audio",
transformationParams: {
"f": "aac",
"br": 192
}
}
});

See the Audio Processing API for the full list of transformationParams when transformation: "audio".

Archives

Using the UrlBuilder to extract the file document.docx from the uploaded ZIP file example.zip:

// import * as Bytescale from "@bytescale/sdk";
// Returns: "https://upcdn.io/1234abc/archive/example.zip?m=extract&artifact=/document.docx"
Bytescale.UrlBuilder.url({
accountId: "1234abc",
filePath: "/example.zip",
options: {
transformation: "archive",
transformationParams: {
m: "extract"
},
artifact: "/document.docx"
}
});

See the Archive Processing API for the full list of transformationParams when transformation: "archive".

Antivirus

Using the UrlBuilder to scan files for viruses, trojans, and other malware:

// import * as Bytescale from "@bytescale/sdk";
// Returns: "https://upcdn.io/1234abc/antivirus/example.zip"
Bytescale.UrlBuilder.url({
accountId: "1234abc",
filePath: "/example.zip",
options: {
transformation: "antivirus"
}
});

See the Antivirus API for full details about the JSON response structure.

Authentication

The Bytescale JavaScript SDK requires a Bytescale API key, and optionally a JWT:

API keys

You must always provide a valid apiKey to the Bytescale JavaScript SDK.

With API key auth, the requester has access to the resources configured in the API key's permissions.

  • Secret API keys: can perform all API operations (see the Bytescale JavaScript SDK).

  • Public API keys: can perform file uploads and file downloads only. File overwrites, file deletes, and all other destructive operations cannot be performed using public API keys.

You must always use public API keys (e.g. public_***) in your client-side code.

JWTs (Optional)

When using public API keys you can optionally pass a JWT to extend the requester's permissions beyond that of the API key. In addition, you can configure your API key to make it reject requests that aren't accompanied by a valid JWT. This prevents users from taking your API key and using it outside of your application.

JWTs are issued by your application and are verified by Bytescale using a public key certificate.

To use JWTs, please use the Bytescale JavaScript SDK AuthManager »

UploadManager

Use the UploadManager to upload files, strings, BLOBs, buffers, and streams to Bytescale.

upload

Uploads a file, string, BLOB, buffer, or stream as the data parameter. (size is only required if the data is a stream.)

Signature

function upload(params: UploadManagerParams): Promise<FileDetails>

Parameters

See details: UploadManagerParams

Result

{
"accountId": String,
"etag": String | Null,
"filePath": String,
"fileUrl": String,
"lastModified": Integer,
"mime": String,
"originalFileName": String | Null,
"size": Integer,
"tags": String[]
}

See details: FileDetails

Example

import * as Bytescale from "@bytescale/sdk";
const uploadManager = new Bytescale.UploadManager({
apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
});
uploadManager
.upload({
"data": "Hello World"
})
.then(
result => console.log(result),
error => console.error(error)
);

AuthManager

Use the AuthManager to authenticate browser requests to the Bytescale API and Bytescale CDN using JWTs.

For server-side requests, we recommend using secret API keys instead of JWTs. If you prefer to use JWTs but are not running your code in the browser, such as in a desktop application, you will need to handle JWTs manually according to the authentication docs »

Instructions:

  1. Create a JWT endpoint.

  2. Call AuthManager.beginAuthSession in your client-side code (see instructions below).

  3. The Bytescale SDK will authenticate all subsequent requests to the Bytescale API and CDN using JWTs.

To learn more about private files, authentication, and JWTs, please see: Authentication »

beginAuthSession

Begins a JWT auth session with the Bytescale API and Bytescale CDN.

You must first create a JWT endpoint in your backend API.

After calling this method, the Bytescale SDK will periodically acquire a JWT from your backend API, which then be used to authenticate subsequent requests to the Bytescale API and CDN from the browser.

You can only call this method if isAuthSessionActive() === false else an error will be returned.

You should call this method after the user has signed into your web app.

After calling this method:

  1. You must await the returned promise before attempting to perform any downloads or API operations that require authentication.

    isAuthSessionActive() will return true immediately after beginAuthSession() is called (but before the promise resolves).

    isAuthSessionReady() will return true only after the promise succeeds, so can also be used to check for auth readiness.

  2. You can then use private file URLs in src elements in img/video/audio elements, etc.

You can only call this method in the browser. For server-side requests, we recommend using secret API keys instead of JWTs. If you prefer to use JWTs but are not running your code in the browser, such as in a desktop application, you will need to handle JWTs manually according to the authentication docs »

Signature

function beginAuthSession(params: BeginAuthSessionParams): Promise<void>

Parameters

See details: BeginAuthSessionParams

Example

import * as Bytescale from "@bytescale/sdk";
async function onSignIn() {
// The URL for your auth API endpoint.
// - For help implementing your auth API endpoint, see: https://www.bytescale.com/docs/auth/generating-jwts
// Your URL must:
// - Return a JWT as plain text.
// - Return a 'content-type: text/plain' response header.
// - Return a 200 status code.
// - Return a signed JWT (i.e. the JWT must include 2x "." characters) using RS256.
// - The public key certificate must be added to the Bytescale Dashboard.
// - The JWT must not be wrapped with "".
const authUrl = "https://your-web-app/your-auth-url";
// Headers required by your auth API endpoint (e.g. 'authorization' header).
const authHeaders = () => Promise.resolve({
authorization: "some auth token"
});
// Wait for authentication to complete:
await Bytescale.AuthManager.beginAuthSession({
accountId: "YOUR_ACCOUNT_ID", // e.g. "W142hJk"
authUrl,
authHeaders,
// Optional:
// - To support modern browsers that block third-party cookies (like Safari),
// you should consider enabling service workers by uncommenting the below.
// - Before uncommenting, you must implement the "/bytescale-auth-sw.js" script.
// - See: https://www.bytescale.com/docs/types/BeginAuthSessionParams#serviceWorkerScript
// serviceWorkerScript: "/bytescale-auth-sw.js"
});
}
// Call this after your user signs in:
await onSignIn();
// After the 'onSignIn' promise completes:
// - You can start referencing private files in <img> elements, etc.
// - You can start performing other operations permitted by the JWT in your client-side code.
// (e.g. file deletions, file uploads to specific folders, etc.)

endAuthSession

Ends a JWT auth session with the Bytescale API and Bytescale CDN.

Signature

function endAuthSession(): Promise<void>

Parameters

This method takes no parameters.

isAuthSessionActive

Checks if an authenticated Bytescale API and Bytescale CDN session is active.

This is true immediately after the beginAuthSession() method is called.

Check this flag before attempting to call beginAuthSession(): beginAuthSession() will fail if isAuthSessionActive() === true.

Signature

function isAuthSessionActive(): boolean

Parameters

This method takes no parameters.

Result

Returns a boolean value.

isAuthSessionReady

Checks if an authenticated Bytescale API and Bytescale CDN session is active and ready to authenticate HTTP requests.

This is true only after the beginAuthSession() promise succeeds (i.e. when private files are ready to be loaded).

Check this flag before attempting to load private files (e.g. when rendering <img> elements that reference private files).

Signature

function isAuthSessionReady(): boolean

Parameters

This method takes no parameters.

Result

Returns a boolean value.

UploadApi

Client methods for the Upload API.

Use the UploadManager instead of calling these methods directly.

uploadFromUrl

Upload from a URL with a single HTTP request:

Signature

function uploadFromUrl(params: UploadFromUrlParams): Promise<BasicUploadResponse>

Parameters

See details: UploadFromUrlParams

Result

{
"accountId": String,
"etag": String,
"filePath": String,
"fileUrl": String
}

See details: BasicUploadResponse

Example

import * as Bytescale from "@bytescale/sdk";
const uploadApi = new Bytescale.UploadApi({
apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
});
uploadApi
.uploadFromUrl({
"accountId": "YOUR_ACCOUNT_ID",
"uploadFromUrlRequest": {
"url": "https://assets.bytescale.com/example.jpg"
}
})
.then(
result => console.log(result),
error => console.error(error)
);

beginMultipartUpload

Begins a new multipart file upload process.

Signature

function beginMultipartUpload(params: BeginMultipartUploadParams): Promise<BeginMultipartUploadResponse>

Parameters

See details: BeginMultipartUploadParams

Result

See details: BeginMultipartUploadResponse

Example

import * as Bytescale from "@bytescale/sdk";
const uploadApi = new Bytescale.UploadApi({
apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
});
uploadApi
.beginMultipartUpload({
"accountId": "YOUR_ACCOUNT_ID",
"beginMultipartUploadRequest": {
"size": 43182
}
})
.then(
result => console.log(result),
error => console.error(error)
);

completeUploadPart

Marks an upload part as uploaded.

You must call this endpoint after you have successfully issued a PUT request to the uploadUrl on the corresponding UploadPart.

Signature

function completeUploadPart(params: CompleteUploadPartParams): Promise<CompleteMultipartUploadResponse>

Parameters

See details: CompleteUploadPartParams

Result

Arbitrary JSON Object

See details: CompleteMultipartUploadResponse

Example

import * as Bytescale from "@bytescale/sdk";
const uploadApi = new Bytescale.UploadApi({
apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
});
uploadApi
.completeUploadPart({
"accountId": "YOUR_ACCOUNT_ID",
"completeUploadPartRequest": {
"etag": "33a64df551425fcc55e4d42a148795d9f25f89d4"
},
"uploadId": "Kd759aLFxttm69kZ",
"uploadPartIndex": 7
})
.then(
result => console.log(result),
error => console.error(error)
);

getUploadPart

Gets a remaining upload part for a multipart file upload.

Signature

function getUploadPart(params: GetUploadPartParams): Promise<UploadPart>

Parameters

{
"accountId": String,
"uploadId": String,
}

See details: GetUploadPartParams

Result

See details: UploadPart

Example

import * as Bytescale from "@bytescale/sdk";
const uploadApi = new Bytescale.UploadApi({
apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
});
uploadApi
.getUploadPart({
"accountId": "YOUR_ACCOUNT_ID",
"uploadId": "Kd759aLFxttm69kZ",
"uploadPartIndex": 7
})
.then(
result => console.log(result),
error => console.error(error)
);

listUploadParts

Lists the remaining upload parts for a multipart file upload.

An empty array is returned when the upload is complete.

Signature

function listUploadParts(params: ListUploadPartsParams): Promise<UploadPartList>

Parameters

{
"accountId": String,
"uploadId": String
}

See details: ListUploadPartsParams

Result

See details: UploadPartList

Example

import * as Bytescale from "@bytescale/sdk";
const uploadApi = new Bytescale.UploadApi({
apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
});
uploadApi
.listUploadParts({
"accountId": "YOUR_ACCOUNT_ID",
"uploadId": "Kd759aLFxttm69kZ"
})
.then(
result => console.log(result),
error => console.error(error)
);

FileApi

Client methods for the File API.

downloadFile

Downloads a file in its original/unprocessed state.

Signature

function downloadFile(params: DownloadFileParams): Promise<BinaryResult>

Parameters

{
"accountId": String,
"cache": Boolean,
"cache_ttl": Number,
"cache_ttl_404": Number,
"filePath": String,
"version": String
}

See details: DownloadFileParams

Result

{
"blob": Function,
"json": Function,
"stream": Function,
"text": Function
}

See details: BinaryResult

Example

import * as Bytescale from "@bytescale/sdk";
const fileApi = new Bytescale.FileApi({
apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
});
fileApi
.downloadFile({
"accountId": "YOUR_ACCOUNT_ID",
"filePath": "/uploads/image.jpg"
})
.then(
result => console.log(result),
error => console.error(error)
);

processFile

Processes a file and returns the result.

Signature

function processFile(params: ProcessFileParams): Promise<BinaryResult>

Parameters

{
"accountId": String,
"artifact": String,
"cache": Boolean,
"cache_only": Boolean,
"cache_perm": String,
"cache_ttl": Number,
"cache_ttl_404": Number,
"filePath": String,
"version": String
}

See details: ProcessFileParams

Result

{
"blob": Function,
"json": Function,
"stream": Function,
"text": Function
}

See details: BinaryResult

Example

import * as Bytescale from "@bytescale/sdk";
const fileApi = new Bytescale.FileApi({
apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
});
fileApi
.processFile({
"accountId": "YOUR_ACCOUNT_ID",
"filePath": "/uploads/image.jpg",
"transformation": "image",
"transformationParams": [
{
"w": 800,
"h": 600,
"fit": "crop"
}
]
})
.then(
result => console.log(result),
error => console.error(error)
);

processFileAndSave

Processes a file and saves the result.

Signature

function processFileAndSave(params: ProcessFileAndSaveParams): Promise<ProcessFileAndSaveResponse>

Parameters

See details: ProcessFileAndSaveParams

Result

Arbitrary JSON Object

See details: ProcessFileAndSaveResponse

Example

import * as Bytescale from "@bytescale/sdk";
const fileApi = new Bytescale.FileApi({
apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
});
fileApi
.processFileAndSave({
"accountId": "YOUR_ACCOUNT_ID",
"filePath": "/source/image.jpg",
"processFileAndSaveRequest": {
"destination": "/destination/image.jpg"
},
"transformation": "image",
"transformationParams": [
{
"w": 800,
"h": 600,
"fit": "crop"
}
]
})
.then(
result => console.log(result),
error => console.error(error)
);

getFileDetails

Gets the full details (e.g. metadata, tags, etc.) for a file.

Signature

function getFileDetails(params: GetFileDetailsParams): Promise<FileDetails>

Parameters

{
"accountId": String,
"filePath": String
}

See details: GetFileDetailsParams

Result

{
"accountId": String,
"etag": String | Null,
"filePath": String,
"fileUrl": String,
"lastModified": Integer,
"mime": String,
"originalFileName": String | Null,
"size": Integer,
"tags": String[]
}

See details: FileDetails

Example

import * as Bytescale from "@bytescale/sdk";
const fileApi = new Bytescale.FileApi({
apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
});
fileApi
.getFileDetails({
"accountId": "YOUR_ACCOUNT_ID",
"filePath": "/uploads/image.jpg"
})
.then(
result => console.log(result),
error => console.error(error)
);

copyFile

Copies a file synchronously.

Signature

function copyFile(params: CopyFileParams): Promise<CopyFileResponse>

Parameters

See details: CopyFileParams

Result

{
"status": String
}

See details: CopyFileResponse

Example

import * as Bytescale from "@bytescale/sdk";
const fileApi = new Bytescale.FileApi({
apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
});
fileApi
.copyFile({
"accountId": "YOUR_ACCOUNT_ID",
"copyFileRequest": {
"destination": "/destination/file.txt",
"source": "/source/file.txt"
}
})
.then(
result => console.log(result),
error => console.error(error)
);

copyFileBatch

Copies multiple files asynchronously.

Signature

function copyFileBatch(params: CopyFileBatchParams): Promise<AsyncResponse>

Parameters

See details: CopyFileBatchParams

Result

{
"jobDocs": String,
"jobId": String,
"jobType": String,
"jobUrl": String
}

See details: AsyncResponse

Example

import * as Bytescale from "@bytescale/sdk";
const fileApi = new Bytescale.FileApi({
apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
});
fileApi
.copyFileBatch({
"accountId": "YOUR_ACCOUNT_ID",
"copyFileBatchRequest": {
"files": [
{
"destination": "/destination/file.txt",
"source": "/source/file.txt"
}
]
}
})
.then(
result => console.log(result),
error => console.error(error)
);

deleteFile

Deletes a file synchronously.

Requires a secret_* API key. Alternatively, you can use a public_* API key and JWT-based auth.

Signature

function deleteFile(params: DeleteFileParams): Promise<void>

Parameters

{
"accountId": String,
"filePath": String
}

See details: DeleteFileParams

Example

import * as Bytescale from "@bytescale/sdk";
const fileApi = new Bytescale.FileApi({
apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
});
fileApi
.deleteFile({
"accountId": "YOUR_ACCOUNT_ID",
"filePath": "/uploads/image.jpg"
})
.then(
result => console.log(result),
error => console.error(error)
);

deleteFileBatch

Deletes multiple files asynchronously.

Requires a secret_* API key. Alternatively, you can use a public_* API key and JWT-based auth.

Signature

function deleteFileBatch(params: DeleteFileBatchParams): Promise<AsyncResponse>

Parameters

See details: DeleteFileBatchParams

Result

{
"jobDocs": String,
"jobId": String,
"jobType": String,
"jobUrl": String
}

See details: AsyncResponse

Example

import * as Bytescale from "@bytescale/sdk";
const fileApi = new Bytescale.FileApi({
apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
});
fileApi
.deleteFileBatch({
"accountId": "YOUR_ACCOUNT_ID",
"deleteFileBatchRequest": {
"files": [
"/uploads/image.jpg"
]
}
})
.then(
result => console.log(result),
error => console.error(error)
);

FolderApi

Client methods for the Folder API.

putFolder

Creates or updates the folder specified by the folderPath.

If the folder's ancestors do not exist, they will be created automatically (with empty FolderSettings).

Note: you don't need to create folders before uploading files to them.

Requires a secret_* API key. Alternatively, you can use a public_* API key and JWT-based auth.

Signature

function putFolder(params: PutFolderParams): Promise<FolderDetails>

Parameters

See details: PutFolderParams

Result

See details: FolderDetails

Example

import * as Bytescale from "@bytescale/sdk";
const folderApi = new Bytescale.FolderApi({
apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
});
folderApi
.putFolder({
"accountId": "YOUR_ACCOUNT_ID",
"putFolderRequest": {
"folderPath": "/uploads"
}
})
.then(
result => console.log(result),
error => console.error(error)
);

getFolderDetails

Gets the full details (e.g. permission, storage layer, etc.) for a folder.

Returns an empty object if no settings have been configured for this folder.

Requires a secret_* API key. Alternatively, you can use a public_* API key and JWT-based auth.

Signature

function getFolderDetails(params: GetFolderDetailsParams): Promise<FolderDetails>

Parameters

{
"accountId": String,
"folderPath": String
}

See details: GetFolderDetailsParams

Result

See details: FolderDetails

Example

import * as Bytescale from "@bytescale/sdk";
const folderApi = new Bytescale.FolderApi({
apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
});
folderApi
.getFolderDetails({
"accountId": "YOUR_ACCOUNT_ID",
"folderPath": "/uploads"
})
.then(
result => console.log(result),
error => console.error(error)
);

listFolder

Lists the folder's contents.

The result may be paginated: subsequent pages can be requested by passing the cursor from the response into the next request.

Pagination is complete when the response includes isPaginationComplete=true.

Signature

function listFolder(params: ListFolderParams): Promise<ListFolderResponse>

Parameters

{
"accountId": String,
"cursor": String,
"dryRun": Boolean,
"folderPath": String,
"includeFiles": Boolean,
"limit": Integer,
"recursive": Boolean
}

See details: ListFolderParams

Result

See details: ListFolderResponse

Example

import * as Bytescale from "@bytescale/sdk";
const folderApi = new Bytescale.FolderApi({
apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
});
folderApi
.listFolder({
"accountId": "YOUR_ACCOUNT_ID",
"folderPath": "/uploads"
})
.then(
result => console.log(result),
error => console.error(error)
);

copyFolder

Copies a folder asynchronously.

You can use ListFolder to preview the operation using the dryRun parameter.

Signature

function copyFolder(params: CopyFolderParams): Promise<AsyncResponse>

Parameters

See details: CopyFolderParams

Result

{
"jobDocs": String,
"jobId": String,
"jobType": String,
"jobUrl": String
}

See details: AsyncResponse

Example

import * as Bytescale from "@bytescale/sdk";
const folderApi = new Bytescale.FolderApi({
apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
});
folderApi
.copyFolder({
"accountId": "YOUR_ACCOUNT_ID",
"copyFolderRequest": {
"destination": "/destination/folder",
"source": "/source/folder",
"recursive": true
}
})
.then(
result => console.log(result),
error => console.error(error)
);

copyFolderBatch

Copies multiple folders asynchronously.

You can use ListFolder to preview the operation using the dryRun parameter.

Signature

function copyFolderBatch(params: CopyFolderBatchParams): Promise<AsyncResponse>

Parameters

See details: CopyFolderBatchParams

Result

{
"jobDocs": String,
"jobId": String,
"jobType": String,
"jobUrl": String
}

See details: AsyncResponse

Example

import * as Bytescale from "@bytescale/sdk";
const folderApi = new Bytescale.FolderApi({
apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
});
folderApi
.copyFolderBatch({
"accountId": "YOUR_ACCOUNT_ID",
"copyFolderBatchRequest": {
"folders": [
{
"destination": "/destination/folder",
"source": "/source/folder",
"recursive": true
}
]
}
})
.then(
result => console.log(result),
error => console.error(error)
);

deleteFolder

Deletes a folder asynchronously.

You can use ListFolder to preview the operation using the dryRun parameter.

External storage: external files are only deleted when you directly delete a file or subfolder of a folder that has external storage configured. If you delete the folder itself, only the mapping is removed.

Requires a secret_* API key. Alternatively, you can use a public_* API key and JWT-based auth.

Signature

function deleteFolder(params: DeleteFolderParams): Promise<AsyncResponse>

Parameters

See details: DeleteFolderParams

Result

{
"jobDocs": String,
"jobId": String,
"jobType": String,
"jobUrl": String
}

See details: AsyncResponse

Example

import * as Bytescale from "@bytescale/sdk";
const folderApi = new Bytescale.FolderApi({
apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
});
folderApi
.deleteFolder({
"accountId": "YOUR_ACCOUNT_ID",
"deleteFolderRequest": {
"folderPath": "/uploads"
}
})
.then(
result => console.log(result),
error => console.error(error)
);

deleteFolderBatch

Deletes multiple folders asynchronously.

You can use ListFolder to preview the operation using the dryRun parameter.

External storage: external files are only deleted when you directly delete a file or subfolder of a folder that has external storage configured. If you delete the folder itself, only the mapping is removed.

Requires a secret_* API key. Alternatively, you can use a public_* API key and JWT-based auth.

Signature

function deleteFolderBatch(params: DeleteFolderBatchParams): Promise<AsyncResponse>

Parameters

See details: DeleteFolderBatchParams

Result

{
"jobDocs": String,
"jobId": String,
"jobType": String,
"jobUrl": String
}

See details: AsyncResponse

Example

import * as Bytescale from "@bytescale/sdk";
const folderApi = new Bytescale.FolderApi({
apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
});
folderApi
.deleteFolderBatch({
"accountId": "YOUR_ACCOUNT_ID",
"deleteFolderBatchRequest": {
"folders": [
{
"folderPath": "/uploads"
}
]
}
})
.then(
result => console.log(result),
error => console.error(error)
);

JobApi

Client methods for the Job API.

getJob

Gets information on a background job.

Requires a secret_* API key.

Signature

function getJob(params: GetJobParams): Promise<JobSummary>

Parameters

{
"accountId": String,
"jobId": String,
"jobType": String
}

See details: GetJobParams

Result

{
"accountId": String,
"created": Integer,
"code": String,
"details": Object,
"message": String,
"timestamp": String
},
"jobDocs": String,
"jobId": String,
"jobType": String,
"jobUrl": String,
"lastUpdated": Integer,
"status": String,
}

See details: JobSummary

Example

import * as Bytescale from "@bytescale/sdk";
const jobApi = new Bytescale.JobApi({
apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
});
jobApi
.getJob({
"accountId": "YOUR_ACCOUNT_ID",
"jobId": "01ARZ3NDEKTSV4RRFFQ69G5FAV",
"jobType": "AntivirusJob"
})
.then(
result => console.log(result),
error => console.error(error)
);

listRecentJobs

Lists the 10 most recently created jobs for the specified job type(s).

Requires a secret_* API key.

Signature

function listRecentJobs(params: ListRecentJobsParams): Promise<ListRecentJobsResponse>

Parameters

{
"accountId": String,
"jobType": String[]
}

See details: ListRecentJobsParams

Result

See details: ListRecentJobsResponse

Example

import * as Bytescale from "@bytescale/sdk";
const jobApi = new Bytescale.JobApi({
apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
});
jobApi
.listRecentJobs({
"accountId": "YOUR_ACCOUNT_ID",
"jobType": [
"AntivirusJob"
]
})
.then(
result => console.log(result),
error => console.error(error)
);

cancelJob

Cancels an in-progress background job.

Requires a secret_* API key.

Signature

function cancelJob(params: CancelJobParams): Promise<void>

Parameters

{
"accountId": String,
"jobId": String,
"jobType": String
}

See details: CancelJobParams

Example

import * as Bytescale from "@bytescale/sdk";
const jobApi = new Bytescale.JobApi({
apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
});
jobApi
.cancelJob({
"accountId": "YOUR_ACCOUNT_ID",
"jobId": "01ARZ3NDEKTSV4RRFFQ69G5FAV",
"jobType": "AntivirusJob"
})
.then(
result => console.log(result),
error => console.error(error)
);

CacheApi

Client methods for the Cache API.

resetCache

Resets the Bytescale CDN cache for a specific path, path prefix, or for your entire account.

You can choose to reset the edge cache, or permanent cache, or both caches.

Warning: Resetting the permanent cache (by setting resetPermanentCache: true) may lead to a significant increase in processing time if numerous file transformations need to be re-performed upon their next request.

Recommended: Prevent cache resets by adding a ?v=<etag> querystring parameter to your URLs. This ensures your URLs change when your files change, eliminating the need for cache resets. The etag field is returned by GetFileDetails and all upload operations, and can be saved to your database.

Example patterns:

"/*"

"/raw/example.jpg"

"/image/example.jpg"

"/image/customers/abc/*"

You may only use * at the end of the pattern. You must not include your account ID prefix in the pattern.

Signature

function resetCache(params: ResetCacheParams): Promise<AsyncResponse>

Parameters

See details: ResetCacheParams

Result

{
"jobDocs": String,
"jobId": String,
"jobType": String,
"jobUrl": String
}

See details: AsyncResponse

Example

import * as Bytescale from "@bytescale/sdk";
const cacheApi = new Bytescale.CacheApi({
apiKey: "YOUR_API_KEY" // e.g. "secret_xxxxx"
});
cacheApi
.resetCache({
"accountId": "YOUR_ACCOUNT_ID",
"resetCacheRequest": {
"pattern": "/raw/example.jpg",
"resetEdgeCache": true,
"resetPermanentCache": true
}
})
.then(
result => console.log(result),
error => console.error(error)
);

Was this section helpful? Yes No

You are using an outdated browser.

This website requires a modern web browser -- the latest versions of these browsers are supported: