For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /api/angular-lynx/media/file-picker.md.

LynxFilePicker

Lets someone pick documents from their phone, such as a PDF, a spreadsheet or a CSV, and save a file your app made where they choose. import { LynxFilePicker, FilePickerError, FILE_PICKER_MAX_BYTES, type FilePickerOptions, type FilePickerErrorCode, type PickedFile, type SaveFile } from '@blotch/angular-lynx';

Lynx has no <input type="file"> and no downloads, and LynxImagePicker only offers photos. Use this for an expense receipt, a CV or a contract to upload, or an invoice or report to export.

Turn it on

Add filePicker to the build target's options in angular.json:

angular.json
"options": {
  "filePicker": true
}

What it adds:

  • iOS: the module that opens UIDocumentPickerViewController.
  • Android: the module, and the lines that launch the system's document picker and save screen.

Neither platform asks the person for a permission, so there's no reason to give. They choose each file or place, and the app reads or writes only that.

Without it, the native code behind the picker is left out of both apps, and pick() and save() reject with unavailable.

For a folder of its own in the iOS Files app, under On My iPhone, also set "fileSharing": true. The person can then save a file there and pick it again later. It adds UIFileSharingEnabled and LSSupportsOpeningDocumentsInPlace to the iOS app. Android has no such folder: its picker already shows Downloads.

See Turn on device features for every setting.

Usage

import { Component, inject, signal } from '@angular/core';
import {
  FilePickerError,
  LYNX_ELEMENTS,
  LynxFilePicker,
} from '@blotch/angular-lynx';
import { Expenses } from './expenses';

@Component({
  selector: 'app-expense',
  imports: [LYNX_ELEMENTS],
  template: `
    <view (bindtap)="attach()"><text>Attach receipt</text></view>
    <view (bindtap)="export()"><text>Export CSV</text></view>
    <text>{{ status() }}</text>
  `,
})
export class Expense {
  readonly #files = inject(LynxFilePicker);
  readonly #expenses = inject(Expenses);
  readonly status = signal('');

  async attach() {
    try {
      const [receipt] = await this.#files.pick({
        types: ['application/pdf', 'image/*'],
      });
      if (!receipt) return; // The person closed the picker.
      await this.#expenses.upload(receipt.blob, receipt.name);
      this.status.set(`Attached ${receipt.name}`);
    } catch (error) {
      if (error instanceof FilePickerError && error.code === 'too-large') {
        this.status.set('That file is over 20 MB');
      } else {
        throw error;
      }
    }
  }

  async export() {
    const csv = new Blob([this.#expenses.toCsv()], { type: 'text/csv' });
    const saved = await this.#files.save({ blob: csv, name: 'expenses.csv' });
    this.status.set(saved ? 'Exported' : '');
  }
}

Expenses stands for the app's own service.

API

LynxFilePicker

@Injectable({ providedIn: 'root' })
class LynxFilePicker {
  pick(options?: FilePickerOptions): Promise<readonly PickedFile[]>;
  recover(): Promise<readonly PickedFile[]>;
  save(file: SaveFile): Promise<boolean>;
}
PlatformPickSave
iOSUIDocumentPickerViewController: iCloud Drive, On My iPhone and other apps' providersThe same picker, exporting a copy where the person chooses
AndroidThe system's document picker (ACTION_OPEN_DOCUMENT): Downloads, Drive and othersIts save screen (ACTION_CREATE_DOCUMENT)
Web previewAn <input type="file">A download, which always resolves true
Unit tests with the testing libraryWhat setPickedFiles() gives, or []Recorded for savedFiles()
Lynx ExplorerRejects with unavailableRejects with unavailable

LynxFilePicker.pick()

pick(options?: FilePickerOptions): Promise<readonly PickedFile[]>;

Opens the picker and resolves with the files picked, or with [] when the person closes it without choosing. Rejects with a FilePickerError, or with a TypeError for a type that isn't a MIME type or an extension.

One picker can be open at a time. Picking again while one is open:

  • On iOS and Android, rejects with failed.
  • In the web preview, resolves the open pick with [].

LynxFilePicker.recover()

recover(): Promise<readonly PickedFile[]>;

Resolves with the files the person picked while Android restarted the app, which no pick() was left to resolve with, or with [] when there are none. Rejects with a FilePickerError with too-large or failed when they couldn't be read, as pick() does.

Android can end the app's screen while the picker is in front, when it needs the memory or with "Don't keep activities" on, and start it again when the person has chosen. The app starts again with it, so the pick() that opened the picker has gone. Call recover() as the app starts:

// In the Expense component above.
constructor() {
  void this.#attachLost();
}

async #attachLost() {
  // Files picked just before Android restarted the app, or [].
  const lost = await this.#files.recover();
  for (const file of lost) {
    await this.#expenses.upload(file.blob, file.name);
    this.status.set(`Attached ${file.name}`);
  }
}
  • It resolves with the files once, read with the same 20 MiB limit as the lost pick().
  • It waits while Android still has to hand the restarted app the result, until the picker closes.
  • It reads the files only when it's called, so an app that never calls it doesn't read them.
  • Files nobody asks for aren't handed over after a minute, and are dropped when another picker or save screen opens, even if the person cancels it, or when the person closes the app or the app ends.
  • A save() lost the same way needs no call: the Android app writes the file where the person chose as soon as they choose. Nothing tells the restarted app, since its save() has gone.
Platformrecover()
AndroidThe files picked while Android restarted the app
iOS, web preview, Lynx Explorer, unit tests[]: iOS doesn't end an app's screen while a picker is open

FilePickerOptions

type FilePickerOptions = {
  readonly types?: readonly string[];
  readonly multiple?: boolean;
};
OptionDescription
typesThe kinds of file the person can pick, as an <input type="file">'s accept lists them (below). Any file without it
multipleWhether the person can pick more than one file. false by default

types takes MIME types (application/pdf), a family (image/*) or extensions (.docx).

PickedFile

type PickedFile = {
  readonly blob: Blob;
  readonly name: string;
  readonly type: string;
  readonly size: number;
};
PropertyDescription
blobThe file's bytes, ready to upload with HttpClient, fetch or a library such as Firebase Storage
nameIts name, such as receipt.pdf
typeIts MIME type, the same as blob.type. application/octet-stream when the platform doesn't know it
sizeIts size in bytes, the same as blob.size

LynxFilePicker.save()

save(file: SaveFile): Promise<boolean>;

type SaveFile = {
  readonly blob: Blob;
  readonly name: string;
};

Lets the person choose where to save the file, under name, which they can change. The Blob's type tells the platform what kind of file it is.

Resolves with true once it's written, or false when they close the screen without saving. Rejects with a FilePickerError, or with a TypeError without a Blob and a name.

FILE_PICKER_MAX_BYTES

The most bytes one pick, all its files together, or one save carries: 20 MiB. The bytes cross between the platform and your app as text, which phones with little memory can hold at this size. A larger file rejects with too-large, before it's read.

FilePickerError

class FilePickerError extends Error {
  readonly code: FilePickerErrorCode;
}

type FilePickerErrorCode = 'unavailable' | 'too-large' | 'failed';
codeWhen
unavailableThe app has no file picker: it was built without "filePicker": true, or it runs in Lynx Explorer
too-largeThe files picked, or the file to save, are over FILE_PICKER_MAX_BYTES
failedThe picker couldn't open, another was open, or a file couldn't be read or written. message says which

Testing

The testing library stands in for the person. Until a spec calls setPickedFiles(), they close the picker; savedFiles() lists what the app saved:

import {
  fireEvent,
  render,
  savedFiles,
  screen,
  setPickedFiles,
  waitForUpdate,
} from '@blotch/angular-lynx-testing-library';

setPickedFiles([
  { name: 'receipt.pdf', type: 'application/pdf', content: pdfBytes },
]);
await render(Expense);
fireEvent.tap(screen.getByText('Attach receipt'));
await waitForUpdate();
expect(screen.getByText('Attached receipt.pdf')).toBeInTheDocument();

fireEvent.tap(screen.getByText('Export CSV'));
await waitForUpdate();
expect(savedFiles()).toMatchObject([
  { name: 'expenses.csv', type: 'text/csv' },
]);

Under the testing library's fake module, recover() resolves with []. A stand-in for LynxFilePicker in a component that calls it needs it too, such as recover: async () => [].