Using Storage SDK
Use the JavaScript Storage SDK to upload, download, share, list, inspect, and delete files after completing Upload and Download Your First File. The examples use an initialized client, the app-files bucket from that quickstart, and browser File objects named file or updatedFile. Select the bucket before calling a storage method:
const files = client.storage.from("app-files");
Pass a path relative to the selected bucket. For example, uploads/ada.png identifies a file in app-files. Use the same path to replace, download, inspect, or delete that file. The file and updatedFile values in the examples are files selected by the user, as in the quickstart. Each operation needs a matching Data Grant for its path and action; see Storage Setup and Configuration.
Storage methods return { data, error }. Check error before using data. When a storage operation fails, error is a RelationalStorageError.
Upload or Replace a File
Use upload(path, body, options?) to upload a file. The following example sets its content type and cache-control value:
const upload = await files.upload("uploads/ada.png", file, {
contentType: file.type,
cacheControl: "3600",
});
if (upload.error) throw upload.error;
To replace a file at the same path, call update(path, body, options?):
const replacement = await files.update(
"uploads/ada.png",
updatedFile,
{ contentType: "image/png" },
);
if (replacement.error) throw replacement.error;
Upload a File in Parts
Use uploadResumable(path, body, options?) to upload a file in parts and finalize it. In this section, file is a video File selected by the user. This example uses the SDK’s configured chunk size:
const upload = await files.uploadResumable("uploads/demo.mp4", file);
if (upload.error) throw upload.error;
The SDK uses a 16 MiB chunk size when the initialized app has no other configured value. An explicit chunkSize must be a positive safe integer number of bytes.
For direct control of a multipart session, use these bucket-scoped methods:
createResumableUpload(path, options?)creates a session.resumeUpload(path, uploadId, body, options?)continues a known session. Setoptions.startPartwhen resuming after completed parts; otherwise, the SDK starts at part 1.commitResumableUpload(path, uploadId)finalizes the uploaded file.abortResumableUpload(path, uploadId)cancels the multipart upload.
To monitor progress or pause an upload, create a task with createResumableUploadTask(path, body, options?):
const task = files.createResumableUploadTask(
"uploads/demo.mp4",
file,
{
onProgress(bytesUploaded, bytesTotal) {
console.log(bytesUploaded + " of " + bytesTotal + " bytes uploaded");
},
onStateChange(state) {
console.log("Upload state:", state);
},
},
);
const result = await task.start();
if (result.error) throw result.error;
console.log(task.state);
console.log(result.data);
console.log(task.uploadId);
console.log(task.bytesTransferred);
console.log(task.totalBytes);
A task can be idle, running, paused, success, error, or aborted. While it runs, pause() stops the active request and returns a session snapshot when an upload ID exists. The snapshot contains the bucket, path, and upload ID, but not the completed-part position. Call resume() on the same idle, paused, or failed task and check its { data, error } result. Call abort() to request cancellation of the server-side upload; an aborted task cannot be resumed.
Download a File
Use download(path) to retrieve a file as a Blob. The following example creates a browser object URL from the result:
const download = await files.download("uploads/ada.png");
if (download.error) throw download.error;
const imageUrl = URL.createObjectURL(download.data);
When the app no longer needs the object URL, release it with URL.revokeObjectURL(imageUrl).
Create URLs for Downloads and Uploads
Use createSignedUrl() when you need a temporary download link, or createSignedUploadUrl() when another client needs to upload a file. getPublicUrl() also returns a time-limited signed download URL despite its name. A path named public does not itself make a file readable.
Get a Public-Style URL
Use getPublicUrl(path, expiresIn?) to get a public-style URL backed by a signed URL. Without expiresIn, the SDK requests a one-hour lifetime:
const publicUrl = await files.getPublicUrl("uploads/ada.png");
if (publicUrl.error) throw publicUrl.error;
const downloadLink = publicUrl.data.publicUrl;
Use downloadLink as a link target in your app. The URL expires, so don’t treat it as a permanent file address.
Create Signed Download URLs
Use createSignedUrl(path, expiresIn, options?) for one file, or createSignedUrls(paths, expiresIn, options?) for several files. Both methods require expiresIn, measured in seconds. In this example, 3600 sets a one-hour lifetime:
const single = await files.createSignedUrl(
"uploads/ada.png",
3600,
);
if (single.error) throw single.error;
const multiple = await files.createSignedUrls(
["uploads/ada.png", "uploads/grace.png"],
3600,
);
if (multiple.error) throw multiple.error;
const downloadLink = single.data.signedUrl;
const downloadLinks = multiple.data.map((item) => item.signedUrl);
Use downloadLink for the first file or a URL from downloadLinks for its corresponding file.
Creating a signed download URL requires a Data Grant that permits SELECT for the create-signed-url operation. Give the generated URL only to its intended recipient. For grant details, see Granting Access to Storage Operations.
Upload with a Signed URL
Use createSignedUploadUrl(path, options?) to create an upload URL and token. The SDK does not accept an expiration value for this call. Pass the returned path and token to uploadToSignedUrl(path, token, body, options?):
const signed = await files.createSignedUploadUrl("uploads/signed-ada.png");
if (signed.error) throw signed.error;
const uploaded = await files.uploadToSignedUrl(
signed.data.path,
signed.data.token,
file,
{ contentType: file.type },
);
if (uploaded.error) throw uploaded.error;
Creating the URL and uploading with its token are separate requests. Check both results for errors.
List and Inspect Files
Use list(path?, options?) to list files under a path. This example requests up to 20 results, then searches and sorts that returned page by name:
const listed = await files.list("uploads", {
limit: 20,
search: "ada",
sortBy: {
column: "name",
order: "asc",
},
});
if (listed.error) throw listed.error;
The SDK applies search and name sorting to the returned page, not to every file in the bucket.
Use info(path) or getMetadata(path) to retrieve the same file metadata object. Use exists(path) to check whether the file exists:
const info = await files.info("uploads/ada.png");
if (info.error) throw info.error;
const metadata = await files.getMetadata("uploads/ada.png");
if (metadata.error) throw metadata.error;
const existence = await files.exists("uploads/ada.png");
if (existence.error) throw existence.error;
const exists = existence.data;
exists is a boolean. The SDK returns false when the service responds with HTTP 404; other failed responses appear in error.
Delete Files
To delete a file from the selected bucket, pass its bucket-relative path to remove(paths). The method accepts an array, so you can include more than one path:
const removed = await files.remove(["uploads/ada.png"]);
if (removed.error) throw removed.error;
A Data Grant must permit DELETE for this operation. For grant details, see Granting Access to Storage Operations.
Handle Storage Errors and Permissions
Check each method’s error value before using data. On failure, read error.message and error.status; error.code, error.details, and error.hint might also be present. A status of 0 can indicate a client-side or network failure.
If a request is denied, confirm the selected bucket and relative path. Then check the app’s Data Role and the grant for that action, path, and content type. For the grant requirements, see Storage Access Control with DDS. For other failure cases, see Errors and Troubleshooting.