Skip to main content

Guide | File Upload and Download

Many internal apps involve working with files. For example: downloading a CSV to the user's browser, uploading images to your server, or displaying PDF previews inline on the page.

Compose is built to support all of these use cases.

File upload

You can upload files from the browser to your app using the built in ui.fileDrop component, which supports files up to 10 megabtyes each.

Files are returned to your app as an array of objects. Each object has the following shape:

// File object in Compose
{
buffer: Buffer;
name: string;
type: string;
}

Learn more about Buffers here.

See the following example:

import { Compose, Page, UI } from "@composehq/sdk"
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

function handler({ page, ui }: { page: Page, ui: UI }) {
let files: { buffer: Buffer, name: string, type: string }[] = [];

function onFiles(newFiles: { buffer: Buffer, name: string, type: string }[]) {
newFiles.forEach(file => {
const filePath = path.join(__dirname, file.name);
fs.writeFileSync(filePath, file.buffer);
});

files = [...files, ...newFiles];
page.update();
}

page.add(() => ui.fileDrop("pdf-file-drop", {
label: "Drop files here",
acceptedFileTypes: ["application/pdf"],
onChange: onFiles
}))

page.add(() => ui.cond(files.length > 0, {
true: ui.text(`Received ${files.length} files.`),
false: ui.text("No files received yet.")
}))
}

const app = new Compose.App({
name: "File Upload",
handler
})

File download

Compose allows you to seamlessly download files from your app to a user's computer using the page.download() method.

The page.download() method accepts a Buffer and filename string, which is sent to the browser and downloaded to the user's device.

import { Compose, Page, UI } from "@composehq/sdk";
import fs from 'fs';

function handler({ page, ui }: { page: Page, ui: UI }) {
function onDownload() {
const fileName = "image.png";

// Read the file into a Buffer
const buffer = fs.readFileSync(pathToFile);

// Download to user's computer
page.download(buffer, fileName)
}

page.add(() => ui.button("download-btn", {
label: "Download PDF",
onClick: onDownload
}))
}

const app = new Compose.App({
name: "File Download",
handler
})