phibac developer docs

Upload and show files

What you will do

You will let users attach a photo to a note: upload the file with files.upload, keep its ID in the note, show it with files.url, and remove it with files.delete.

A few words used on this page:

  • An app is the web app you build. A user is the person who uses it; the notes and photos belong to them, in their own private storage on the server.
  • A collection is one kind of data, here notes, and each saved note is a record. The collection's schema lists its fields; the server checks every record against it.
  • The SDK (@phibac/sdk) is the JavaScript library your page uses to talk to the phibac server.
  • A file is stored next to the records, not inside one. A record holds only the file's ID, which starts with f_, in a field of type fileRef.

Before you start

You need the notes app from Build your first app, all the way to step 9: the local server running in terminal 1 (npx phibac dev), the com.example.notes.note collection published, and Vite serving the page on http://localhost:5173. Stop Vite (Ctrl-C in its terminal) while you run the commands in step 1, and start it again for What you should see.

This guide replaces the quickstart's index.html and src/main.ts with versions that keep everything the quickstart page does (notes, the Pinned box and the two lists) and add photos, so the guides after this one can build on the same app. If you followed other guides, which replace these files with their own, this puts the quickstart page back.

Steps

1. Add a fileRef field

A file belongs to a collection, and a record points to it through a fileRef field. Add a photo field to the notes collection: in pb.config.ts, add fileRef to the import and the photo line to the fields. With the quickstart's file, the result is (keep your own app value):

import { defineApp, collection, string, boolean, fileRef } from "phibac";

export default defineApp({
  app: "app_...",
  collections: {
    "com.example.notes.note": collection({
      version: 1,
      description: "A note written by the user",
      fields: {
        text: string({ description: "Note text", maxLength: 20000, required: true }),
        pinned: boolean({ description: "Whether the note is pinned", indexed: true }),
        photo: fileRef({ description: "A photo attached to the note" }),
      },
    }),
  },
});

If you followed Define your data or Query, sort and live updates, your notes already have this photo field: keep your file as it is. Then npx phibac deploy below prints same (version 1.x, nothing to publish) for each collection instead of publishing, which is fine.

Publish the change and generate the types:

npx phibac deploy
npx phibac generate

A new optional field is not a breaking change, so npx phibac deploy publishes it as a new minor version of the same major version. After the quickstart, you should see:

Previewing 1 collection for app app_01M7E9YEJZZSYKAAB14AMBBJPR on http://localhost:8787
com.example.notes.note  additive (will become version 1.1)
published com.example.notes.note version 1.1
Published 1 collection.

src/pb-types.ts now has the new field. A fileRef field is a string in TypeScript:

// Generated from published collection schemas. Do not edit by hand.

/** A note written by the user */
export interface ComExampleNotesNoteV1 {
  /** A photo attached to the note */
  photo?: string;
  /** Whether the note is pinned */
  pinned?: boolean;
  /** Note text */
  text: string;
}

export const SCHEMA_MAJORS = {
  "com.example.notes.note": 1,
} as const;

The server checks only that a fileRef value looks like a file ID (f_ and 26 letters and digits). It does not check that the file exists.

2. Add a file input to the page

Replace index.html with this file. It is the quickstart's page with a file input added:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Notes</title>
  </head>
  <body>
    <h1>Notes</h1>
    <button type="button" id="sign-in">Sign in</button>
    <p id="message" role="alert"></p>
    <form id="note-form" hidden>
      <input id="note-text" placeholder="Write a note" aria-label="Note text" />
      <label><input type="checkbox" id="note-pinned" /> Pinned</label>
      <input type="file" id="note-photo" accept="image/*" aria-label="Photo" />
      <button type="submit">Add note</button>
    </form>
    <h2>Pinned notes</h2>
    <ul id="pinned-list"></ul>
    <h2>All notes</h2>
    <ul id="all-list"></ul>
    <script type="module" src="/src/main.ts"></script>
  </body>
</html>

accept="image/*" only makes the browser offer pictures first: the server accepts files of any type.

3. Upload, show and remove photos

Replace src/main.ts with this file, with your app ID in place of app_.... It does everything the quickstart's file does, and handles photos:

import { connect, PbError, type Backend, type Collection, type PbRecord } from "@phibac/sdk";
import { SCHEMA_MAJORS, type ComExampleNotesNoteV1 as Note } from "./pb-types";

// The app ID that phibac init printed, and the local server that phibac dev runs.
const APP = "app_...";
const BASE_URL = "http://localhost:8787";
const COLLECTION = "com.example.notes.note";

const signIn = document.querySelector<HTMLButtonElement>("#sign-in")!;
const message = document.querySelector<HTMLParagraphElement>("#message")!;
const form = document.querySelector<HTMLFormElement>("#note-form")!;
const noteText = document.querySelector<HTMLInputElement>("#note-text")!;
const notePinned = document.querySelector<HTMLInputElement>("#note-pinned")!;
const notePhoto = document.querySelector<HTMLInputElement>("#note-photo")!;
const pinnedList = document.querySelector<HTMLUListElement>("#pinned-list")!;
const allList = document.querySelector<HTMLUListElement>("#all-list")!;

let backend: Backend | null = null;
let notes: Collection<Note> | null = null;

// Shows an error's code and message. textContent shows text as typed: it never runs it as HTML.
function showError(e: unknown): void {
  message.textContent = e instanceof PbError ? `${e.code}: ${e.message}` : String(e);
}

// One <img> per file, made once and reused, because each files.url() call asks the server again.
const images = new Map<string, HTMLImageElement>();

function photo(b: Backend, fileId: string): HTMLImageElement {
  const known = images.get(fileId);
  if (known !== undefined) return known;
  const img = document.createElement("img");
  img.alt = "Photo attached to the note";
  img.width = 200;
  // The address files.url() gives works only for a short time: enough for the browser to load the image.
  b.files.url(fileId).then((url) => (img.src = url), showError);
  images.set(fileId, img);
  return img;
}

// Removes a note's photo: deletes the file, then clears the field that names it.
async function removePhoto(b: Backend, c: Collection<Note>, record: PbRecord<Note>, fileId: string): Promise<void> {
  try {
    await b.files.delete(fileId);
    images.delete(fileId);
    // null removes a field. The cast is needed because the generated type does not allow null.
    await c.update(record.rkey, { photo: null } as unknown as Partial<Note>);
  } catch (e) {
    showError(e);
  }
}

// The pinned list shows text only. Each note shows its status: "pending" until the server has it, then "synced".
function showPinned(records: PbRecord<Note>[]): void {
  pinnedList.replaceChildren(
    ...records.map((record) => {
      const item = document.createElement("li");
      item.textContent = `${record.data.text} (${record.status})`;
      return item;
    }),
  );
}

// The full list also shows each photo, with a button that removes it.
function showAll(b: Backend, c: Collection<Note>, records: PbRecord<Note>[]): void {
  allList.replaceChildren(
    ...records.map((record) => {
      const item = document.createElement("li");
      const text = document.createElement("p");
      text.textContent = `${record.data.text} (${record.status})`;
      item.append(text);
      const fileId = record.data.photo;
      if (fileId !== undefined) {
        const remove = document.createElement("button");
        remove.type = "button";
        remove.textContent = "Remove photo";
        remove.addEventListener("click", () => void removePhoto(b, c, record, fileId));
        item.append(photo(b, fileId), remove);
      }
      return item;
    }),
  );
}

// connect() may open the sign-in popup, and browsers allow a popup only from a click.
signIn.addEventListener("click", async () => {
  try {
    const b = await connect({ app: APP, baseUrl: BASE_URL, schemaMajors: SCHEMA_MAJORS });
    const c = b.collection<Note>(COLLECTION);
    backend = b;
    notes = c;
    // Live updates: each function runs now, and again whenever the matching notes change.
    c.orderBy("createdAt", "desc").subscribe((records) => showAll(b, c, records));
    c.where("pinned", "==", true).subscribe(showPinned);
    signIn.hidden = true;
    form.hidden = false;
    message.textContent = "";
  } catch (e) {
    showError(e);
  }
});

form.addEventListener("submit", async (event) => {
  event.preventDefault();
  const text = noteText.value.trim();
  const file = notePhoto.files?.[0];
  if (backend === null || notes === null || text === "") return;
  try {
    const note: Note = { text, pinned: notePinned.checked };
    // Upload first: the note keeps the file ID that the upload returns.
    if (file !== undefined) note.photo = await backend.files.upload(file, { collection: COLLECTION });
    await notes.create(note);
    form.reset();
    message.textContent = "";
  } catch (e) {
    showError(e);
  }
});

The three file calls:

  • files.upload(blob, { collection }) stores a file, such as the File the user picked in a file input, and returns its file ID. collection is the collection whose records will point to the file: one your app published, or one of its own sandbox.<name> collections. Save the ID in a fileRef field, as the form does. Any type of file is accepted. Its type (for example image/png) is sent with it and given back when the file is downloaded. A file can be at most 100 MB.
  • files.url(fileId) returns a download address for the file. It works for 5 minutes: reuse an address while it is valid, ask for a new one when it has expired, and never store one in a record. Anyone who has the address can download the file until it expires, without signing in.
  • files.delete(fileId) deletes the file and frees its space at once. Only the app that owns the file's collection can delete it.

SDK reference gives every option and error of the three calls.

What the server does not do for you:

  • Uploads and deletes are not queued. Unlike create and update, they need a connection: offline, or when anything goes wrong, they fail with an error and nothing is saved. In the form above, a failed upload means the note is not created either, so the user can try again.
  • Records and files are not linked. Deleting a record does not delete its files, and deleting a file does not change the records that name it. To remove a note with its photo, delete the file and then the note. A record can be left pointing at a deleted file: files.url then fails with not_found.

4. Know who can read a file

A file can be downloaded by the app that uploaded it, and by any other app the user has allowed to read the collection the file belongs to (see Read another app's data). The user sees every file their apps stored in their account area on the server, on the Storage and plan page (http://localhost:8787/account/billing for the local server), and can delete any of them there.

On the local server, files are kept on your computer in ./.pb/blobs, inside the folder you started npx phibac dev from.

What you should see

  1. Start Vite again (npx vite --port 5173 --strictPort), open http://localhost:5173, press Sign in and finish signing in. Your earlier notes appear under All notes, and the pinned ones under Pinned notes.
  2. Type a note, tick Pinned, pick a picture with the file input and press Add note. The note appears under Pinned notes, and under All notes with your picture and a Remove photo button, marked (synced) once the server has it.
  3. Press Remove photo. The picture disappears and the note stays in both lists.
  4. Switch the browser to offline in its developer tools, pick a picture and press Add note. The page shows network: … and no note is added. Switch back online and add it again.

Common problems

  • network when uploading or deleting a file. The device is offline or the server cannot be reached. Uploads and deletes are not queued: let the user try again when the device is back online.
  • payload_too_large. The file is larger than 100 MB. Make it smaller before uploading, for example by resizing an image.
  • not_found saying the collection "has no published schema". The collection you passed to files.upload is not published. Run npx phibac deploy, check the name, or use a sandbox.<name> collection for files only your app needs.
  • forbidden saying your app "may not add files to" a collection. The collection belongs to another app. An app can add files only to the collections it published and to its own sandbox collections; consent to read another app's collection does not allow uploads.
  • forbidden saying your app "may not delete file". Only the app that owns the file's collection can delete the file. The user can delete it on the Storage and plan page of their account.
  • not_found from files.url. The file ID is wrong, the upload did not finish, or the file was deleted. Clear the field that still names it.
  • not_found from files.delete. The file ID is wrong or the file is already deleted. Clear the field that still names it.
  • consent_required from files.url. The file belongs to another app's collection, and the user has not allowed your app to read that collection. Call requestAccess() on the collection from a click, as in Read another app's data.
  • A picture does not load when you use an address from files.url again later. The address works only for 5 minutes; after that the download is refused. Call files.url again each time you show the file in a new place.

Next step

Read another app's data builds a second app that asks the user's permission to read the notes, then shows them.