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
- from() - Specify the bucket
- throwOnError() - throws an exception on error
File Operations
- upload() - Upload files
- update() - Update file
- download() - Download file
- remove() - Remove a file
- move() - Move file
- copy() - Copy file
URL management
- createSignedUrl() - Create a signature URL
- createSignedUrls() - Batch create pre-signed URLs
- getPublicUrl() - Get public URL
- createSignedUploadUrl() - Create an upload signature URL
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.
参数
File path, for example 'images/photo.jpg'
File content, supporting types such as File, Blob, ArrayBuffer, Buffer, Stream
Upload options
返回
示例
// 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);
}
// Upload files and configure settings
const { data, error } = await app.storage
.from()
.upload("images/photo.jpg", file, {
cacheControl: "max-age=3600",
contentType: "image/jpeg",
metadata: {
author: "John Doe",
uploadedAt: new Date().toISOString(),
},
});
if (error) {
console.error("Upload failed:", error);
} else {
console.log("upload succeeded:", data);
}
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.
参数
File path
New File Content
Upload options
返回
示例
// 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);
}
// Update file and modify metadata
const { data, error } = await app.storage
.from()
.update("images/photo.jpg", newFile, {
cacheControl: "max-age=7200",
metadata: {
updatedAt: new Date().toISOString(),
version: "2.0",
},
});
if (error) {
console.error("update failed:", error);
} else {
console.log("file updated:", data.path);
}
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.
参数
File ID
Image conversion options (only applicable to images)
返回
示例
// 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();
}
// Download and convert the image to a thumbnail
const { data: thumbnail, error } = await app.storage
.from()
.download("cloud://envId.xxx/images/photo.jpg", {
width: 300,
height: 200,
quality: 80,
});
if (thumbnail) {
// Display thumbnails
const url = URL.createObjectURL(thumbnail);
document.getElementById("thumbnail").src = url;
}
// Download and convert the image format
const { data: webpImage, error } = await app.storage
.from()
.download("cloud://envId.xxx/images/photo.jpg", {
format: "webp",
quality: 90,
});
if (webpImage) {
console.log("converted to WebP format");
}
remove
remove(
fileIds: string[]
): Promise<{ data: { id: string }[]; error: null } | { data: null; error: StorageError }>
Delete one or more files.
参数
Array of file IDs to be deleted
返回
示例
// 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);
}
// Batch deleting multiple files
const { data, error } = await app.storage
.from()
.remove([
"cloud://envId.xxx/images/photo1.jpg",
"cloud://envId.xxx/images/photo2.jpg",
"cloud://envId.xxx/documents/file.pdf",
]);
if (error) {
console.error("delete failed:", error);
} else {
console.log(`delete successfully ${data.length} files`);
}
move
move(
fromPath: string,
toPath: string
): Promise<{ data: { message: string }; error: null } | { data: null; error: StorageError }>
Move files to a new location.
参数
Source file path
Target file path
返回
示例
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);
}
// Rename file (move to same directory with new name)
const { data, error } = await app.storage
.from()
.move("images/photo.jpg", "images/new-photo.jpg");
if (error) {
console.error("rename failed:", error);
} else {
console.log("rename succeeded");
}
copy
copy(
fromPath: string,
toPath: string
): Promise<{ data: { path: string }; error: null } | { data: null; error: StorageError }>
Copy the file to a new location.
参数
Source file path
Target file path
返回
示例
// 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);
}
// Create a copy under the same directory
const { data, error } = await app.storage
.from()
.copy("images/photo.jpg", "images/photo-copy.jpg");
if (error) {
console.error("create copy failed:", error);
} else {
console.log("copy created:", 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.
参数
File ID
URL validity period (seconds)
Image conversion options
返回
示例
// 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
}
// Create a temporary link for the thumbnail
const { data, error } = await app.storage
.from()
.createSignedUrl("cloud://envId.xxx/images/photo.jpg", 3600, {
width: 300,
height: 200,
quality: 80,
});
if (error) {
console.error("creation failed:", error);
} else {
// Use the thumbnail link
document.getElementById("thumbnail").src = data.signedUrl;
}
Create a short-term share link valid for 5 minutes
const { data, error } = await app.storage
.from()
.createSignedUrl("cloud://envId.xxx/images/photo.jpg", 300);
if (error) {
console.error("creation failed:", error);
} else {
// Share this link, it will automatically expire in 5 minutes
navigator.clipboard.writeText(data.signedUrl);
alert("Share link copied to clipboard");
}
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.
参数
File ID array
URL validity period (seconds)
返回
示例
// 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}`);
});
}
// Batch create thumbnail links
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 {
// Display all thumbnails
const gallery = document.getElementById("gallery");
data.forEach((item) => {
const img = document.createElement("img");
img.src = item.signedUrl;
gallery.appendChild(img);
});
}
getPublicUrl
getPublicUrl(
fileId: string,
options?: TransformOptions
): { data: { publicUrl: string } }
Get the public access URL of the file (without signature).
参数
File ID
Image conversion options
返回
示例
// 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).
// Get the public link of the thumbnail
const { data } = await app.storage
.from()
.getPublicUrl("cloud://envId.xxx/images/photo.jpg", {
width: 300,
height: 200,
quality: 80,
});
// for use in img tags
document.getElementById("thumbnail").src = data.publicUrl;
info
info(
fileId: string
): Promise<{ data: FileInfo; error: null } | { data: null; error: StorageError }>
Get file detailed information.
参数
File ID
返回
示例
// 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);
}
// Display file details on the interface
const { data, error } = await app.storage
.from()
.info("cloud://envId.xxx/documents/report.pdf");
if (data) {
const sizeInMB = (data.size / 1024 / 1024).toFixed(2);
document.getElementById("fileName").textContent = data.name;
document.getElementById("fileSize").textContent = `${sizeInMB} MB`;
document.getElementById("createdAt").textContent = new Date(
data.created_at
).toLocaleString();
}
exists
exists(
fileId: string
): Promise<{ data: boolean; error: null } | { data: null; error: StorageError }>
Check whether the file exists.
参数
File ID
返回
示例
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");
}
Check whether the file already exists before uploading
const { data: exists } = await app.storage
.from()
.exists("cloud://envId.xxx/images/photo.jpg");
if (exists) {
// File already exists, ask whether to overwrite
const shouldOverwrite = confirm("File already exists, whether to overwrite?");
if (shouldOverwrite) {
await app.storage.from().update("images/photo.jpg", file);
}
} else {
// File does not exist, direct upload
await app.storage.from().upload("images/photo.jpg", file);
}
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.
参数
File ID
Upload options
返回
示例
// 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,
},
});
}
// Implement direct upload on the client
async function uploadFileDirectly(file) {
// Get a signature upload URL
const { data, error } = await app.storage
.from()
.createSignedUploadUrl(`cloud://envId.xxx/uploads/${file.name}`);
if (error) {
console.error("Fail to get upload URL:", error);
return;
}
// 2. Direct upload to cloud storage
const uploadResponse = await fetch(data.signedUrl, {
method: "PUT",
body: file,
headers: {
"Content-Type": file.type,
},
});
if (uploadResponse.ok) {
console.log("upload succeeded");
} else {
console.error("Upload failed");
}
}
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 API | Supabase-style API | Description |
|---|---|---|
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);
// Supabase-style
const { data, error } = await app.storage
.from()
.upload("images/photo.jpg", file);
if (error) {
console.error("Upload failed:", error);
} else {
console.log("File ID:", data.id);
}
Get a temporary link
// Traditional method
const res = await app.getTempFileURL({
fileList: [
{
fileID: "cloud://envId.xxx/images/photo.jpg",
maxAge: 3600,
},
],
});
const url = res.fileList[0].tempFileURL;
// Supabase-style
const { data, error } = await app.storage
.from()
.createSignedUrl("cloud://envId.xxx/images/photo.jpg", 3600);
if (data) {
const url = data.signedUrl;
}
Delete files
// Traditional method
const result = await app.deleteFile({
fileList: ["cloud://xxx.jpg"],
});
// Supabase-style
const { data, error } = await app.storage
.from()
.remove(["cloud://envId.xxx/images/photo.jpg"]);
Download files
// Traditional method
const result = await app.downloadFile({
fileID: "cloud://xxx.jpg",
});
// Supabase-style
const { data: blob, error } = await app.storage
.from()
.download("cloud://envId.xxx/images/photo.jpg");
if (blob) {
Use a Blob object
const url = URL.createObjectURL(blob);
}
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.
5. How long is the maximum validity period of a temporary link?
Recommended: no more than 7 days (604800 seconds).