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
Server API Key:
storage.read/storage.write(bucket and file management); client upload/download goes through user Session + bucket/file permissions.Preview capabilities depend on the instance's image processing component; for self-hosted troubleshooting see troubleshooting.md.
Usage workflow
Create bucket:
storage.createBucket({ bucketId, name, permissions, fileSecurity, enabled, maximumFileSize, allowedFileExtensions, compression, encryption, antivirus })(permissions,fileSecurity,enabled,maximumFileSize,allowedFileExtensions,compression,encryption,antivirusare all optional).Bucket-level
permissionsis the "front door" (e.g.,create("users"),read("users"),read("label:admin")).fileSecurity: trueenables file-level permissions (the "room door"); whenfalse, only bucket-level applies.
Upload:
storage.createFile({ bucketId, fileId, file, permissions })(permissionsoptional);fileuses the SDK'sInputFile(form File /fromPath/fromBuffer/fromBytes; on the Node side import from the SDK'sfilesubpath). When file-level$permissionsis absent, the default rule matching the bucket configuration is applied; for fine-grained control, explicitly pass anPermissionlist.Read:
getFilemetadata;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).Manage:
listFiles/updateFile(rename, permissions) /deleteFile.File Token (no-Cookie scenarios): the Server SDK's
Tokensservice issues time-limited tokens for specified files —createFileToken({ bucketId, fileId, expire })(expireoptional),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}.Usage:
storage.getUsage({ range }),storage.getBucketUsage({ bucketId, range })(Console / management-plane figures).
Key parameters and returns
| Invocation | Key parameters | Returns / notes |
|---|---|---|
createBucket | fileSecurity、maximumFileSize、allowedFileExtensions | Models.Bucket |
createFile | bucketId, fileId (ID.unique()), file, permissions (optional) | Models.File ($id, name, mimeType, sizeOriginal, $permissions) |
getFilePreview | bucketId, fileId, width (optional), height (optional), gravity (optional), quality (optional), format etc. | URL string (no authentication) |
getFileDownload / getFileView | bucketId, fileId | URL string |
createFileToken | bucketId, 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:
Blob URL: use the SDK's
client.call('GET', url, {}, {}, 'arrayBuffer')to make an authenticated request, and only afterURL.createObjectURL(new Blob(...))assign it to<img src>(can be wrapped as auseImageBlob-style Hook).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
413 exceeds the bucket's
maximumFileSize; 400 extension is not inallowedFileExtensions.Deleting others' files fails with 403: file-level
deleteuses the uploader's personal role — for team collaboration change toRole.team(teamId).A leaked Token equals read access to that file while valid:
expireset it short, issue only for necessary files, and have the backend / Function issue it and hand the short link to the frontend; never put the Token-creating API Key in the browser.For long-term team sharing prefer
Permission+ Session; use Tokens only for temporary, no-Cookie scenarios.2.6.0 Security defaults: remote Avatar/Favicon/Screenshot-type fetches are tightened by default; if external resource access fails, first check the instance's security policy rather than disabling protection.
SDK Category Differences
Client SDK (Web): user Session upload / download / preview;
getFilePreview/getFileViewURLs carry no authentication (see above); use Blob URLs for cross-origin scenarios.Server SDK: full bucket and file lifecycle, explicit authorization, File Token issuance (
Tokensservice); Node'sInputFileis imported from thefilesubpath.Console SDK: bucket management (management-plane view) and storage usage (
storage.getUsage/getBucketUsage).Difference entry points: client-sdk/web.md,
server-sdk/nodejs.md.
Example Guide
Language-specific usage is centralized in the language tree
examples/; for Blob URL / Hook wrappers, error comparison tables, and debugging steps seeskills/ob-agentbase/references/storage-permissions.md,skills/ob-agentbase/references/file-tokens.md.
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).
- Node.js (Server)
- Java
- Python
- Go
- REST (curl)
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,
});import io.agentbase.services.Storage;
Storage storage = new Storage(client); // For client initialization, see server-sdk/java.md
// Positional parameter form (permissions / fileSecurity / maximumFileSize etc. have the same semantics as the Node side):
storage.createBucket("attachments", "附件", null, true, true,
26214400L, null, null, true, false, true);from agentbase.services.storage import Storage
storage = Storage(client) # client initialization see examples/python.md
storage.create_bucket(bucket_id='attachments', name='附件',
file_security=True, enabled=True) # permissions takes an array of permission stringsstorage := agentbase.NewStorage(cl) // facade constructor; cl is a Client already loaded with an API Key
_, err := storage.CreateBucket("attachments", "附件",
storage.WithCreateBucketFileSecurity(true),
storage.WithCreateBucketEnabled(true))
// permissions is passed as an array of permission strings; for exact option names refer to the module sourcecurl -sS -X POST "$APPBASE_ENDPOINT/storage/buckets" \
-H 'Content-Type: application/json' \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
-d '{
"bucketId": "app-assets",
"name": "App Assets",
"fileSecurity": true,
"permissions": [
"read(\"users\")",
"update(\"team:dev/owner\")",
"delete(\"team:dev/owner\")",
"create(\"label:admin\")"
]
}'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.
- Node.js (Server)
- Web (user session)
- Java
- Python
- Go
- REST (curl)
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 requestimport { Storage, ID, Permission, Role } from 'agentbase-web-sdk'; // User is logged in
const file = await storage.createFile({
bucketId: 'attachments',
fileId: ID.unique(),
file: document.getElementById('fileInput').files[0], // Form File
});
const download = await storage.getFileDownload({ bucketId: 'attachments', fileId: '<fileId>' });
const previewUrl = storage.getFilePreview('attachments', '<fileId>', 800); // URL string, without authenticationimport io.agentbase.ID;
import io.agentbase.services.Storage;
Storage storage = new Storage(client);
var file = storage.createFile("attachments", ID.unique(),
InputFile.fromPath(java.nio.file.Paths.get("./report.pdf")), null);
storage.getFileDownload("attachments", file.getId()); // Download (redirect / response)
storage.getFilePreview("attachments", file.getId(), 800); // Only builds the URL, does not send an authentication request
// InputFile factories: fromPath / fromFile / fromBytes; parameters such as preview width/height and quality, see source codefrom agentbase.id import ID
from agentbase.input_file import InputFile
from agentbase.services.storage import Storage
storage = Storage(client)
uploaded = storage.create_file(bucket_id='attachments', file_id=ID.unique(),
file=InputFile.from_path('/path/to/report.pdf'))
download: bytes = storage.get_file_download(bucket_id='attachments', file_id=uploaded.id)
preview_url = storage.get_file_preview(bucket_id='attachments', file_id=uploaded.id,
width=800) # Only builds the URL, does not send an authentication request
# view / download return a byte stream; preview requires transformations enabled on the bucketstorage := agentbase.NewStorage(cl)
uploaded, err := storage.CreateFile("attachments", id.Unique(),
file.NewInputFile("./report.pdf", "report.pdf"))
download, err := storage.GetFileDownload("attachments", uploaded.Id) // *[]byte
// PreviewUrl: storage.GetFilePreview("attachments", uploaded.Id) (only builds the URL,
// See module source for options such as width/height / gravity / quality)
_ = downloadcurl -sS -X POST "$APPBASE_ENDPOINT/storage/buckets/app-assets/files" \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
-F fileId="unique()" \
-F 'permissions[]=read("users")' \
-F file="@./pink.png"
# Download: GET /storage/buckets/{bucketId}/files/{fileId}/download (attachment)
# Inline view: /view; image preview: /preview?width=800&height=600 (requires transformations enabled on the bucket)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.
- Node.js (Server)
- Web (user session)
- Java
- Python
- Go
- REST (curl)
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>' });// User Session: list / metadata / delete files the user has permission to operate on
const files = await storage.listFiles({ bucketId: 'attachments' });
const meta = await storage.getFile({ bucketId: 'attachments', fileId: '<fileId>' });
await storage.deleteFile({ bucketId: 'attachments', fileId: '<fileId>' });
// Rename / permission updates go through the server or REST PUT (see the REST tab; permissions are fully replaced)var files = storage.listFiles("attachments", null, null); // queries / search
var meta = storage.getFile("attachments", "<fileId>"); // Metadata only, does not return content
storage.updateFile("attachments", "<fileId>", "report-updated.pdf",
null); // permissions is a full replacement; if omitted, current permissions are retained
storage.deleteFile("attachments", "<fileId>"); // File content is immutablefiles = storage.list_files(bucket_id='attachments') # Pagination via queries
meta = storage.get_file(bucket_id='attachments', file_id='<file_id>') # Metadata only, does not return content
storage.update_file(bucket_id='attachments', file_id='<file_id>',
name='report-updated.pdf') # permissions is a full replacement; omit to keep unchanged
storage.delete_file(bucket_id='attachments', file_id='<file_id>')files, err := storage.ListFiles("attachments") // Pagination via WithListFilesQueries
meta, err := storage.GetFile("attachments", "<fileId>") // Metadata only, does not return content
_, err = storage.UpdateFile("attachments", "<fileId>",
storage.WithUpdateFileName("report-updated.pdf")) // permissions is a full replacement; omit to keep unchanged
_, err = storage.DeleteFile("attachments", "<fileId>")
_, _ = files, meta# List files (paginate via queries[]; total=false skips counting to reduce overhead)
curl -sS "$APPBASE_ENDPOINT/storage/buckets/attachments/files?queries[]=limit(25)&total=false" \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID" -H "X-Appwrite-Key: $APPBASE_API_KEY"
# Metadata: GET /storage/buckets/{bucketId}/files/{fileId}
# Rename / permissions (full replacement, content immutable): PUT
curl -sS -X PUT "$APPBASE_ENDPOINT/storage/buckets/attachments/files/<fileId>" \
-H 'Content-Type: application/json' \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
-d '{"name": "report-updated.pdf", "permissions": ["read(\"label:vip\")"]}'
# Delete: DELETE /storage/buckets/{bucketId}/files/{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.
- Web (user session)
// 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)File Token: short-lived access for no-Cookie scenarios
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.
- Node.js (Server)
- Java
- Python
- Go
- REST (curl)
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>import io.agentbase.services.Tokens;
Tokens tokens = new Tokens(client);
var token = tokens.createFileToken("attachments", "<fileId>",
"2026-10-15T06:38:00.000+00:00"); // expire is nullable; always set a short TTL
// Append the token's secret to /storage/buckets/attachments/files/<fileId>/view?token=<secret>
// Common methods: createFileToken / list / get / update / deletefrom agentbase.services.tokens import Tokens # the services list includes the tokens module
tokens = Tokens(client)
token = tokens.create_file_token(bucket_id='attachments', file_id='<file_id>',
expire='2026-10-15T06:38:00.000+00:00') # Be sure to set a short validity period
# append token.secret to /storage/buckets/attachments/files/<file_id>/view?token=<secret>
# Common methods: create_file_token / list / get / update / deletetokens := agentbase.NewTokens(cl) // facade constructor
token, err := tokens.CreateFileToken("attachments", "<fileId>",
tokens.WithCreateFileTokenExpire("2026-10-15T06:38:00.000+00:00")) // Be sure to set a short validity period
// Append the token's secret to /storage/buckets/attachments/files/<fileId>/view?token=<secret>
// Common methods: CreateFileToken / List / Get / Update / Delete
_ = tokencurl -sS -X POST "$APPBASE_ENDPOINT/tokens/buckets/attachments/files/<fileId>" \
-H 'Content-Type: application/json' \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
-d '{"expire": "2026-10-15T06:38:00.000+00:00"}'
# The response contains a secret (JWT format); assemble the URL: /v1/storage/buckets/attachments/files/<fileId>/view?token=<secret>
# List filename tokens: GET /v1/tokens/buckets/{bucketId}/files/{fileId}; revoke: DELETE /v1/tokens/{tokenId}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.
- Console (Node.js)
- REST (curl)
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 arraycurl -sS "$APPBASE_ENDPOINT/storage/usage?range=30d" \
-b "$APPBASE_CONSOLE_COOKIE" -H "X-Appwrite-Project: $APPBASE_PROJECT_ID"
# Single bucket: GET /storage/buckets/{bucketId}/usage?range=30d (range enumerates 24h / 30d / 90d)
# Key returned fields: filesStorageTotal, storage trends