Skip to main content

Overview

Quick Start

import cloudbase from "@cloudbase/js-sdk";

const app = cloudbase.init({
env: "your-env-id",
});

// Use Supabase-style API
const storage = app.storage.from();

// Upload documents.
const { data, error } = await storage.upload("images/photo.jpg", file);

// Downloading file
const { data: blob } = await storage.download(
"cloud://envId.xxx/images/photo.jpg"
);

// Create a signature URL
const {
data: { signedUrl },
} = await storage.createSignedUrl(
"[images/photo.jpg](cloud://envId.xxx/images/photo.jpg)",
3600
);

// Delete the document.
await storage.remove([
"[images/photo.jpg](cloud://envId.xxx/images/photo.jpg)",
]);

API method

Chained call

File Operations

URL management

File Information


from

from(bucket?: string): this

Specify the bucket to operate, chosen by default the cloud bucket in the environment.

Example:

const storage = app.storage.from();

throwOnError

throwOnError(): this

Set to throw an exception when an error occurs rather than return an error object.

Example:

const storage = app.storage.from().throwOnError();

try {
const { data } = await storage.upload("file.txt", file);
console.log("upload succeeded:", data);
} catch (error) {
console.error("Upload failed:", error);
}

upload

upload(
path: string,
fileBody: FileBody,
fileOptions?: FileOptions
): Promise<{ data: { id: string; path: string; fullPath: string }; error: null } | { data: null; error: StorageError }>

Upload files to cloud storage.

参数

path
string

File path, for example 'images/photo.jpg'

fileBody
FileBody

File content, supporting types such as File, Blob, ArrayBuffer, Buffer, Stream

fileOptions
FileOptions

Upload options

返回

Promise
{ data, error }

示例

// Upload documents.
const { data, error } = await app.storage
.from()
.upload("images/photo.jpg", file);

if (error) {
console.error("Upload failed:", error);
} else {
console.log("upload succeeded:", data);
console.log("File ID:", data.id);
console.log("file path:", data.path);
}

update

update(
path: string,
fileBody: FileBody,
fileOptions?: FileOptions
): Promise<{ data: { id: string; path: string; fullPath: string }; error: null } | { data: null; error: StorageError }>

Update an existing file.

参数

path
string

File path

fileBody
FileBody

New File Content

fileOptions
FileOptions

Upload options

返回

Promise
{ data, error }

示例

// Update file contents
const { data, error } = await app.storage
.from()
.update("images/photo.jpg", newFile);

if (error) {
console.error("update failed:", error);
} else {
console.log("update succeeded:", data);
}

download

download(
fileId: string,
options?: TransformOptions
): Promise<{ data: Blob; error: null } | { data: null; error: StorageError }>

Download a file and return the Blob object. Support the image transformation feature.

参数

fileId
string

File ID

options
TransformOptions

Image conversion options (only applicable to images)

返回

Promise
{ data, error }

示例

// Downloading original file
const { data, error } = await app.storage
.from()
.download("cloud://envId.xxx/images/photo.jpg");

if (data) {
// Create a download link
const url = URL.createObjectURL(data);
const a = document.createElement("a");
a.href = url;
a.download = "photo.jpg";
a.click();
}

remove

remove(
fileIds: string[]
): Promise<{ data: { id: string }[]; error: null } | { data: null; error: StorageError }>

Delete one or more files.

参数

fileIds
string[]

Array of file IDs to be deleted

返回

Promise
{ data, error }

示例

// Deleting a single file
const { data, error } = await app.storage
.from()
.remove(["cloud://envId.xxx/images/photo.jpg"]);

if (error) {
console.error("delete failed:", error);
} else {
console.log("delete successful:", data);
}

move

move(
fromPath: string,
toPath: string
): Promise<{ data: { message: string }; error: null } | { data: null; error: StorageError }>

Move files to a new location.

参数

fromPath
string

Source file path

toPath
string

Target file path

返回

Promise
{ data, error }

示例

Move files to a new location
const { data, error } = await app.storage
.from()
.move("images/old-photo.jpg", "images/archive/photo.jpg");

if (error) {
console.error("move failure:", error);
} else {
console.log("move succeeded:", data.message);
}

copy

copy(
fromPath: string,
toPath: string
): Promise<{ data: { path: string }; error: null } | { data: null; error: StorageError }>

Copy the file to a new location.

参数

fromPath
string

Source file path

toPath
string

Target file path

返回

Promise
{ data, error }

示例

// Copy file to new location
const { data, error } = await app.storage
.from()
.copy("images/photo.jpg", "images/backup/photo.jpg");

if (error) {
console.error("copy failed:", error);
} else {
console.log("copied successfully, file path:", data.path);
}

createSignedUrl

createSignedUrl(
fileId: string,
expiresIn: number,
options?: TransformOptions
): Promise<{ data: { signedUrl: string }; error: null } | { data: null; error: StorageError }>

Create a signed temporary access URL.

参数

fileId
string

File ID

expiresIn
number

URL validity period (seconds)

options
TransformOptions

Image conversion options

返回

Promise
{ data, error }

示例

// Create a temporary link valid for 1 hour
const { data, error } = await app.storage
.from()
.createSignedUrl("cloud://envId.xxx/images/photo.jpg", 3600);

if (error) {
console.error("creation failed:", error);
} else {
console.log("temporary link:", data.signedUrl);
// This link can be accessed directly to the file
}

createSignedUrls

createSignedUrls(
fileIds: string[],
expiresIn: number,
): Promise<{ data: Array<{ path: string; signedUrl: string }>; error: null } | { data: null; error: StorageError }>

Create signed temporary access URLs in batches.

参数

fileIds
string[]

File ID array

expiresIn
number

URL validity period (seconds)

返回

Promise
{ data, error }

示例

// Create temporary links for multiple files at one time
const { data, error } = await app.storage
.from()
.createSignedUrls(
[
"cloud://envId.xxx/images/photo1.jpg",
"cloud://envId.xxx/images/photo2.jpg",
"cloud://envId.xxx/images/photo3.jpg",
],
3600
);

if (error) {
console.error("creation failed:", error);
} else {
data.forEach((item) => {
console.log(`${item.path}: ${item.signedUrl}`);
});
}

getPublicUrl

getPublicUrl(
fileId: string,
options?: TransformOptions
): { data: { publicUrl: string } }

Get the public access URL of the file (without signature).

参数

fileId
string

File ID

options
TransformOptions

Image conversion options

返回

Object
{ data }

示例

// Get the public access link of the file
const { data } = await app.storage
.from()
.getPublicUrl("cloud://envId.xxx/images/photo.jpg");

console.log("public link:", data.publicUrl);
// This link can be used directly (if the file is set to public).

info

info(
fileId: string
): Promise<{ data: FileInfo; error: null } | { data: null; error: StorageError }>

Get file detailed information.

参数

fileId
string

File ID

返回

Promise
{ data, error }

示例

// Get file details
const { data, error } = await app.storage
.from()
.info("cloud://envId.xxx/images/photo.jpg");

if (error) {
console.error("get failed:", error);
} else {
console.log("Filename:", data.name);
console.log("File size:", data.size, "bytes");
console.log("Creation time:", data.created_at);
console.log("Update time:", data.updated_at);
console.log("Metadata:", data.metadata);
}

exists

exists(
fileId: string
): Promise<{ data: boolean; error: null } | { data: null; error: StorageError }>

Check whether the file exists.

参数

fileId
string

File ID

返回

Promise
{ data, error }

示例

Check whether the file exists
const { data: exists, error } = await app.storage
.from()
.exists("cloud://envId.xxx/images/photo.jpg");

if (error) {
console.error("check failed:", error);
} else if (exists) {
console.log("file exists");
} else {
console.log("file not found");
}

createSignedUploadUrl

createSignedUploadUrl(
fileId: string,
options?: { upsert?: boolean }
): Promise<{ data: { signedUrl: string; path: string; token: string }; error: null } | { data: null; error: StorageError }>

Create a pre-signed URL for uploading, allowing the client to directly upload files to cloud storage.

参数

fileId
string

File ID

options
Object

Upload options

返回

Promise
{ data, error }

示例

// Create a pre-signed URL for uploading
const { data, error } = await app.storage
.from()
.createSignedUploadUrl("cloud://envId.xxx/images/photo.jpg");

if (error) {
console.error("creation failed:", error);
} else {
console.log("upload URL:", data.signedUrl);
console.log("upload token:", data.token);

// Use this URL to directly upload files
const formData = new FormData();
formData.append("file", file);

await fetch(data.signedUrl, {
method: "PUT",
body: file,
headers: {
"Content-Type": file.type,
},
});
}

Type definition

FileBody

type FileBody = File | Blob | ArrayBuffer | Buffer | ReadableStream | string;

Supported file content types.

FileOptions

interface FileOptions {
cacheControl?: string; // Cache control, for example 'max-age=3600'
contentType?: string; // File MIME type, for example 'image/jpeg'
metadata?: Record<string, any>; // Custom metadata
upsert?: boolean; // Whether to overwrite the existing file
}

File upload options.

TransformOptions

interface TransformOptions {
width?: number; // Target width
height?: number; // Target height
quality?: number; // Image quality (1-100)
format?: "jpg" | "png" | "webp"; // Output format
}

Image conversion options (only applicable to images).

FileInfo

interface FileInfo {
name: string; // File name
id: string; // File ID
size: number; // File size (bytes)
created_at: string; // Creation time
updated_at: string; // Update time
metadata?: Record<string, any>; // Custom metadata
}

File information object.

StorageError

interface StorageError {
message: string; // Error message
statusCode?: number; // HTTP status code
}

Store error object.


Migration Guide

If you are using the traditional CloudBase cloud storage API, we recommend migrating to the Supabase style API. The following is the comparison table:

API Comparison Table

Traditional APISupabase-style APIDescription
app.uploadFile()app.storage.from().upload()Upload files
app.getTempFileURL()app.storage.from().createSignedUrl()Get temporary link
app.deleteFile()app.storage.from().remove()Delete a file
app.downloadFile()app.storage.from().download()Download a file

Migration Example

Upload a file

// Traditional method
const result = await app.uploadFile({
cloudPath: "images/photo.jpg",
filePath: file,
});

console.log("File ID:", result.fileID);
// Traditional method
const res = await app.getTempFileURL({
fileList: [
{
fileID: "cloud://envId.xxx/images/photo.jpg",
maxAge: 3600,
},
],
});

const url = res.fileList[0].tempFileURL;

Delete files

// Traditional method
const result = await app.deleteFile({
fileList: ["cloud://xxx.jpg"],
});

Download files

// Traditional method
const result = await app.downloadFile({
fileID: "cloud://xxx.jpg",
});

Best Practices

1. Error Handling

Always check the error object:

const { data, error } = await app.storage.from().upload("file.txt", file);

if (error) {
console.error("Operation failed:", error.message);
// Handle error
return;
}

// Use data
console.log("operation succeeded:", data);

Or use the throwOnError() method:

try {
const { data } = await app.storage
.from()
.throwOnError()
.upload("file.txt", file);

console.log("operation succeeded:", data);
} catch (error) {
console.error("Operation failed:", error);
}

2. File path format specification

-Use / to separate directories -Do not start with /. -Use meaningful directory structure

// ✅ Recommendation
"images/avatars/user-123.jpg";
"documents/reports/2024/report.pdf";
"uploads/temp/file-abc.txt";

// ❌ Not recommended
"/images/photo.jpg"; // Do not start with /
"photo.jpg"; // lack of directory structure

3. Image Optimization

Optimize loading speed with image conversion options.

// Get thumbnail
const { data } = await app.storage
.from()
.createSignedUrl("images/large-photo.jpg", 3600, {
width: 300,
height: 300,
quality: 80,
format: "webp", // Use WebP format to reduce file size
});

4. Batch Operation

For operations on multiple files, use batch methods to improve efficiency:

// ✅ Recommend: Batch create pre-signed URLs
const { data } = await app.storage
.from()
.createSignedUrls(["image1.jpg", "image2.jpg", "image3.jpg"], 3600);

// ❌ Not recommended: Create one by one
for (const path of paths) {
await app.storage.from().createSignedUrl(path, 3600);
}

5. Cache Control

Reasonably set cache control headers.

// Static resource: long-term cache
await app.storage.from().upload("images/logo.png", file, {
cacheControl: "max-age=31536000", // 1 year
});

// Dynamic content: short-term cache
await app.storage.from().upload("data/report.json", file, {
cacheControl: "max-age=300", // 5 minutes
});

// No cache
await app.storage.from().upload("temp/data.txt", file, {
cacheControl: "no-cache",
});

FAQs

How to Handle Large File Upload

For large files, recommend using createSignedUploadUrl() to implement direct upload:

const { data } = await app.storage
.from()
.createSignedUploadUrl("large-file.zip");

// Use fetch to upload large files
await fetch(data.signedUrl, {
method: "PUT",
body: largeFile,
});

2. How to achieve breakpoint resume?

CloudBase cloud storage does not directly support breakpoint resumption. We recommend using chunked upload for large files.

async function uploadLargeFile(file, chunkSize = 5 * 1024 * 1024) {
const chunks = Math.ceil(file.size / chunkSize);

for (let i = 0; i < chunks; i++) {
const start = i * chunkSize;
const end = Math.min(start + chunkSize, file.size);
const chunk = file.slice(start, end);

await app.storage.from().upload(`temp/file-${i}`, chunk);
}

// Merge shards (Serverless Cloud Function support is required)
}

3. How to set file access permission

File access permission need to be set in the TCB console under "Permission Control/Policy Management".

4. Which image format conversion

Support JPG, PNG, and WebP format conversion between each other.

Recommended: no more than 7 days (604800 seconds).


Related Resources