Docs
Contents

Object Storage

Overview and use cases

Uploading, downloading, previewing, and permission control for buckets and files; with short-lived access tokens (File Token). When to use: user avatars, attachments, image assets, files that need temporary share links. The permission model (fileSecurity, 404 semantics, cross-origin pitfalls) complements the storage section of permissions.md.

Prerequisites

Usage workflow

  1. Create bucket: storage.createBucket({ bucketId, name, permissions, fileSecurity, enabled, maximumFileSize, allowedFileExtensions, compression, encryption, antivirus }) (permissions, fileSecurity, enabled, maximumFileSize, allowedFileExtensions, compression, encryption, antivirus are all optional).

    • Bucket-level permissions is the "front door" (e.g., create("users"), read("users"), read("label:admin")).

    • fileSecurity: true enables file-level permissions (the "room door"); when false, only bucket-level applies.

  2. Upload: storage.createFile({ bucketId, fileId, file, permissions }) (permissions optional); file uses the SDK's InputFile (form File / fromPath / fromBuffer / fromBytes; on the Node side import from the SDK's file subpath). When file-level $permissions is absent, the default rule matching the bucket configuration is applied; for fine-grained control, explicitly pass an Permission list.

  3. Read: getFile metadata; getFileDownload (download URL / response); getFileView / getFilePreview (preview, with bandwidth, height, gravity, quality, etc. — these two methods only build URL strings and do not issue authenticated requests).

  4. Manage: listFiles / updateFile (rename, permissions) / deleteFile.

  5. File Token (no-Cookie scenarios): the Server SDK's Tokens service issues time-limited tokens for specified files — createFileToken({ bucketId, fileId, expire }) (expire optional), list / get / update / delete; the response contains secret / URL fields for view / preview / download (subject to the current SDK model). Path prefix /v1/tokens/buckets/{bucketId}/files/{fileId}.

  6. Usage: storage.getUsage({ range }), storage.getBucketUsage({ bucketId, range }) (Console / management-plane figures).

Key parameters and returns

InvocationKey parametersReturns / notes
createBucketfileSecurity、maximumFileSize、allowedFileExtensionsModels.Bucket
createFilebucketId, fileId (ID.unique()), file, permissions (optional)Models.File ($id, name, mimeType, sizeOriginal, $permissions)
getFilePreviewbucketId, fileId, width (optional), height (optional), gravity (optional), quality (optional), format etc.URL string (no authentication)
getFileDownload / getFileViewbucketId, fileIdURL string
createFileTokenbucketId, fileId, expire (optional; ISO 8601)Token (short-link credential)

UsageRange Enumeration: 24h / 30d / 90d.

Errors and edge cases: 404 semantics under fileSecurity

Decision chain: bucket-level read matches → allowed directly; no match and fileSecurity: false → 401; no match and fileSecurity: true → query file-level permissions with auth → return if matched, if unmatched return 404 (file_not_found), not 403 — hiding file existence. Troubleshooting rule of thumb: on 404 check permissions first, then existence.

<img> cross-origin pitfall

In a cross-origin HTTP (or cross-site) environment, <img src=".../preview?project=..."> does not carry the Session Cookie (SameSite=None is downgraded when Secure is absent, and img tags cannot carry headers / fallback cookies), the request arrives anonymously → bucket-level read("users") does not match → file-level does not match either → 404. The correct approach:

  1. Blob URL: use the SDK's client.call('GET', url, {}, {}, 'arrayBuffer') to make an authenticated request, and only after URL.createObjectURL(new Blob(...)) assign it to <img src> (can be wrapped as a useImageBlob-style Hook).

  2. File Token: for scenarios that cannot carry Cookies (email links, third parties, SSR-generated previews), the server issues a short-lived Token to generate an accessible URL.

Errors and boundaries

SDK Category Differences

Example Guide

Examples by language

The following provides examples by language, item by item along the usage workflow; each card can switch languages (synced across the page).

Create bucket (bucket-level permission baseline)

By default a bucket grants no user roles — user-side reads / file creation require explicitly configuring permissions; only fileSecurity: true enables file-level permissions. No web tab: bucket creation is a server-side action (Console configures it in the management-plane UI).

import { Client, Storage, Permission, Role } from 'agentbase-node-sdk';

const client = new Client()
    .setEndpoint(process.env.APPBASE_ENDPOINT!)   // Must include /v1
    .setProject(process.env.APPBASE_PROJECT_ID!)
    .setKey(process.env.APPBASE_API_KEY!);        // storage.read / storage.write
const storage = new Storage(client);

await storage.createBucket({
    bucketId: 'attachments',
    name: '附件',
    permissions: [Permission.read(Role.users()), Permission.create(Role.users())],
    fileSecurity: true,      // Enable file-level permissions (the room door)
    enabled: true,
});

Upload / download / preview

createFile's file is wrapped by the SDK's InputFile (on the Node side import from the SDK's file subpath); file-level permissions takes effect only when the bucket enables fileSecurity.

import { Storage, ID, Permission, Role } from 'agentbase-node-sdk';
import { InputFile } from 'agentbase-node-sdk/file';

const file = await storage.createFile({
    bucketId: 'attachments',
    fileId: ID.unique(),
    file: InputFile.fromPath('./report.pdf'),   // or InputFile.fromBuffer(bytes, 'report.pdf')
    permissions: [Permission.read(Role.users())],   // Optional; requires fileSecurity enabled on the bucket
});

await storage.getFileDownload('attachments', file.$id);   // Download (redirect / response)
const previewUrl = storage.getFilePreview('attachments', file.$id, 800);   // Only builds the URL, does not send an authentication request

File management: listFiles / getFile / updateFile / deleteFile

listFiles lists files in a bucket with pagination, getFile fetches metadata (does not return content); updateFile only updates metadata (name and permissions, permissions is a full replacement, semantics same as updateRow); file content is immutable.

const files = await storage.listFiles({ bucketId: 'attachments' });   // Pagination via queries
const meta = await storage.getFile({ bucketId: 'attachments', fileId: '<fileId>' });

await storage.updateFile({
    bucketId: 'attachments',
    fileId: '<fileId>',
    name: 'report-updated.pdf',
    // permissions: [...]   // full replacement: if omitted, current permissions are retained
});

await storage.deleteFile({ bucketId: 'attachments', fileId: '<fileId>' });

Cross-origin <img>: Blob URL (Web only)

In cross-origin environments <img src=".../preview?project=..."> cannot carry the Session Cookie, so fileSecurity the bucket rejects with 404 (file_not_found) — use an SDK authenticated request to fetch the byte stream and convert to a Blob URL.

// getFilePreview / getFileView only build the URL without making a request; use client.call() to make an authenticated request
// (automatically carries credentials: 'include' + X-Fallback-Cookies header); get the ArrayBuffer and convert it to a Blob URL:
const arrayBuffer: ArrayBuffer = await client.call(
    'GET',
    `${ENDPOINT}/storage/buckets/${bucketId}/files/${fileId}/view`,
    {}, {}, 'arrayBuffer'
);
const blobUrl = URL.createObjectURL(new Blob([arrayBuffer]));
imgElement.src = blobUrl;   // On component unmount / refetch: URL.revokeObjectURL(blobUrl)

For scenarios that cannot carry Cookies such as email links, third parties, and SSR previews, the server issues a time-limited token; secret is appended with ?token= to the file's view / preview / download endpoints. No web tab: issuance is a server-side action.

import { Tokens } from 'agentbase-node-sdk';

const tokens = new Tokens(client);
const token = await tokens.createFileToken({
    bucketId: 'attachments',
    fileId: '<fileId>',
    expire: '2026-10-15T06:38:00.000+00:00',   // Optional, ISO 8601; make sure to set a short expiry
});
// Common methods: createFileToken / list / get / update / delete
// Append token.secret to /storage/buckets/{bucketId}/files/{fileId}/view?token=<secret>

Usage (Console / management-plane figures)

Object storage overview and per-bucket aggregate usage go through the Console SDK: management-plane Session / JWT, the client must point to the app project and setMode('admin'); the regular Server SDK (API Key) does not include these aggregate methods, hence no Node tab on this card.

import { Client, Storage, UsageRange } from 'agentbase-console-sdk';

// For initialization see console-sdk/nodejs.md; before querying an app project, point to that project and enter admin mode:
// client.setProject('<projectId>').setMode('admin')
const storage = new Storage(client);

const usage = await storage.getUsage({ range: UsageRange.ThirtyDays });   // '30d'; enum 24h / 30d / 90d
const bucketUsage = await storage.getBucketUsage({ bucketId: 'attachments', range: UsageRange.ThirtyDays });
// Key returns: filesStorageTotal and the storage trend array