Uploading Files
Two architectural patterns to upload binary assets into Cloudizero storage: direct server-side uploads or zero-egress client browser uploads via presigned URLs without burdening your server.
Pattern 1: Direct Backend Upload (Node.js / Server Actions)
Use cz.storage.upload() when processing buffers, file streams, or downloaded assets directly in server environments (Node.js, Express, Next.js Server Actions, etc.):
import { Cloudizero } from "@cloudizero/sdk";
import fs from "fs";
const cz = new Cloudizero({
apiKey: process.env.CLOUDIZERO_API_KEY!,
});
async function uploadReport() {
const buffer = fs.readFileSync("./quarterly-report.pdf");
const asset = await cz.storage.upload({
file: buffer,
fileName: "quarterly-report.pdf",
projectId: "prj_LXAlEW70v24YSc0y",
folderId: "fld_ARaZjwdPpUqXhDHf", // opsional: Folder ID (atau kosongkan untuk root)
mimeType: "application/pdf",
});
console.log("Storage Key:", asset.storageKey || asset.r2Key);
console.log("Delivery URL:", asset.url);
}Pattern 2: Client Direct Upload (Browser Direct Upload via Presigned URL)
For web applications (React, Vue, Next.js) handling client uploads, never expose secret API keys in the browser. Use the presigned ticket handshake: your backend generates a short-lived signed upload URL, and the client browser streams bytes directly to Cloudizero Storage Engine:
Security: Protect Your API Key
CLOUDIZERO_API_KEY in client-side code (NEXT_PUBLIC_*). Secret keys must always reside strictly on your backend server.Step 1: Backend Routes for Presign & Complete
Create API routes in your backend to generate the presigned ticket and record metadata upon completion:
// app/api/upload/presign/route.ts (Next.js App Router / Express)
import { NextResponse } from "next/server";
import { Cloudizero } from "@cloudizero/sdk";
const cz = new Cloudizero({
apiKey: process.env.CLOUDIZERO_API_KEY!,
});
export async function POST(req: Request) {
// 1. Authorize user session from cookies / auth token
const { fileName, fileSize, mimeType, projectId } = await req.json();
// 2. Generate secure signed direct-to-storage upload ticket
const ticket = await cz.storage.createPresignedUpload({
projectId,
fileName,
fileSize,
mimeType,
});
return NextResponse.json(ticket);
}// app/api/upload/complete/route.ts (Next.js App Router)
import { NextResponse } from "next/server";
import { Cloudizero } from "@cloudizero/sdk";
const cz = new Cloudizero({
apiKey: process.env.CLOUDIZERO_API_KEY!,
});
export async function POST(req: Request) {
const body = await req.json();
// Finalize asset & index metadata in Cloudizero Database
const asset = await cz.storage.completeUpload({
fileId: body.fileId,
projectId: body.projectId,
fileName: body.fileName,
mimeType: body.mimeType,
fileSize: body.fileSize,
storageKey: body.storageKey,
});
return NextResponse.json(asset);
}Step 2: Browser Client Component with Progress Bar
The browser requests a presigned ticket, issues an HTTP PUT directly to Cloudizero Storage Engine with accurate byte-level progress reporting, and finalizes with your backend:
// components/direct-uploader.tsx
"use client";
import { useState } from "react";
import type { PresignedUploadResult, UploadedFile } from "@cloudizero/sdk";
export function DirectUploader({ projectId }: { projectId: string }) {
const [progress, setProgress] = useState<number>(0);
const [uploading, setUploading] = useState(false);
const [cdnUrl, setCdnUrl] = useState<string | null>(null);
const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
setUploading(true);
setProgress(0);
try {
// Step 1: Request signed upload ticket from your backend
const presignRes = await fetch("/api/upload/presign", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
fileName: file.name,
fileSize: file.size,
mimeType: file.type || "application/octet-stream",
projectId,
}),
});
const ticket: PresignedUploadResult = await presignRes.json();
// Step 2: Stream binary directly to Cloudizero Storage Engine (Zero-Egress)
await new Promise<void>((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open("PUT", ticket.uploadUrl);
xhr.setRequestHeader("Content-Type", file.type || "application/octet-stream");
xhr.upload.onprogress = (evt) => {
if (evt.lengthComputable) {
setProgress(Math.round((evt.loaded / evt.total) * 100));
}
};
xhr.onload = () => (xhr.status >= 200 && xhr.status < 300 ? resolve() : reject(new Error("PUT upload failed")));
xhr.onerror = () => reject(new Error("Network error during direct upload"));
xhr.send(file);
});
// Step 3: Notify backend to verify asset and register metadata
const completeRes = await fetch("/api/upload/complete", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
fileId: ticket.fileId,
projectId,
fileName: ticket.finalFileName || file.name,
mimeType: file.type || "application/octet-stream",
fileSize: file.size,
storageKey: ticket.storageKey,
}),
});
const recorded: UploadedFile = await completeRes.json();
setCdnUrl(recorded.url || null);
} catch (err) {
console.error("Direct upload failed:", err);
} finally {
setUploading(false);
}
};
return (
<div className="space-y-4">
<input type="file" onChange={handleFileChange} disabled={uploading} />
{uploading && (
<div className="space-y-1">
<p className="text-sm font-medium">Uploading: {progress}%</p>
<div className="w-full bg-muted rounded-full h-2">
<div className="bg-blue-600 h-2 rounded-full transition-all" style={{ width: `${progress}%` }} />
</div>
</div>
)}
{cdnUrl && (
<a href={cdnUrl} target="_blank" rel="noreferrer" className="text-blue-600 text-sm font-medium">
View uploaded media on CDN →
</a>
)}
</div>
);
}Method Signature & Parameters (`UploadOptions`)
| Property | Type | Default | Description |
|---|---|---|---|
| file*required | File | Blob | Buffer | Uint8Array | — | Binary data payload. Accepts native browser File/Blob or Node.js Buffer. |
| fileName*required | string | — | Original filename with extension (e.g. 'banner.webp'). |
| projectId*required | string | — | Prefixed ID of the destination project (e.g. 'prj_...'). |
| folderId | string | null | null (root) | ID of virtual folder to place the file into. |
| mimeType | string | application/octet-stream | MIME media type for storage Content-Type header. |
| width | number | null | null | Image width in pixels (optional relational metadata). |
| height | number | null | null | Image height in pixels (optional relational metadata). |
| onProgress | ({ loaded, total, percent }) => void | undefined | Real-time upload progress callback (browser environments). |
| autoExtract | boolean | undefined (inherits account setting) | Controls whether to extract multi-page PDF documents into WebP images upon upload. |
Return Value (`UploadedFile`)
The promise resolves with an UploadedFile object upon successful completion and database indexing:
| Property | Type | Default | Description |
|---|---|---|---|
| id | string | — | Unique database identifier (Prefixed ID e.g. 'fil_...'). |
| name | string | — | Filename stored in the catalog. |
| storageKey | string | — | Cloudizero Zero-Egress Storage object key path. |
| r2Key | string | — | Backward-compatible alias for storageKey. |
| size | number | — | Size in bytes. |
| mimeType | string | — | MIME media type. |
| url | string | undefined | — | Fully resolved public CDN link if cdnUrl is configured. |