Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 37 ยท Capacitor and Native APIs

Camera and Filesystem

Take photos with the Capacitor Camera plugin, handle permissions and errors, save files with the Filesystem plugin and show them with convertFileSrc in Ionic apps.

Photos are the classic first native feature. Users take a picture, you show it, and you keep it for later. Two Capacitor plugins cover this: Camera, which opens the system camera or photo picker, and Filesystem, which reads and writes files in the app's own storage. In this lesson you will use both, handle the cases where a user says no, and learn why a photo should be saved as a file instead of a giant string in storage.

It builds on Capacitor Overview and Project Setup: plugins are installed with npm, then npx cap sync is run.

Installing and taking a picture

Terminal
npm install @capacitor/camera @capacitor/filesystem
npx cap sync

The Camera plugin has one main call, getPhoto. Real code, read-only:

TypeScript
import { Camera, CameraResultType, CameraSource } from '@capacitor/camera';

export async function takePhoto(): Promise<string | null> {
  try {
    const photo = await Camera.getPhoto({
      quality: 80,
      allowEditing: false,
      resultType: CameraResultType.Uri,   // a path, not the image data
      source: CameraSource.Prompt,        // let the user choose camera or gallery
      width: 1280,                        // downscale large sensors
    });
    return photo.webPath ?? null;         // usable in <img src>
  } catch (error) {
    // Thrown when the user cancels or denies permission
    console.warn('No photo taken', error);
    return null;
  }
}

resultType matters. Base64 returns the whole image as text, which can be several megabytes and slows the web view. Uri returns a reference to a file, and webPath is a URL the web view can display. Prefer Uri for anything you store or list.

Permissions

Both platforms require the user to grant camera access, and the native projects need a usage text. On iOS you add NSCameraUsageDescription (and NSPhotoLibraryUsageDescription for the gallery) to Info.plist; if they are missing the app crashes when the camera opens. Android declares permissions in AndroidManifest.xml; the plugin adds most of them for you.

The plugin can check and ask in advance:

TypeScript
const status = await Camera.checkPermissions();   // { camera: 'prompt', photos: 'granted' }
if (status.camera !== 'granted') {
  const result = await Camera.requestPermissions({ permissions: ['camera'] });
  if (result.camera === 'denied') {
    // Explain why the camera is needed and point to system settings
  }
}

States are prompt, prompt-with-rationale, granted and denied. Once a user has denied the request twice on Android, or once on iOS, asking again does nothing: only the system settings can change it. Design the screen so that a denial leads somewhere useful (for example a file picker or a "type it instead" option).

Never request every permission on first launch. Ask when the user taps the feature that needs it, and say in your own words what it is for. Users deny unexplained prompts, and a denied prompt is hard to undo.

Saving the photo with Filesystem

A webPath can point to a temporary location. To keep a photo, read it and write it into the app's data directory. The Filesystem plugin works with directories (Directory.Data, Directory.Documents, Directory.Cache) and paths relative to them.

TypeScript
import { Filesystem, Directory } from '@capacitor/filesystem';

async function savePhoto(webPath: string): Promise<string> {
  const blob = await (await fetch(webPath)).blob();
  const data = await blobToBase64(blob);            // Filesystem writes base64 text
  const fileName = `photo-${Date.now()}.jpeg`;

  await Filesystem.writeFile({
    path: `photos/${fileName}`,
    data,
    directory: Directory.Data,
    recursive: true,                                 // create missing folders
  });
  return fileName;
}

Later you can list, read or delete:

TypeScript
const { files } = await Filesystem.readdir({ path: 'photos', directory: Directory.Data });
const { uri } = await Filesystem.getUri({ path: 'photos/a.jpeg', directory: Directory.Data });
const src = Capacitor.convertFileSrc(uri);           // URL the web view can load
await Filesystem.deleteFile({ path: 'photos/a.jpeg', directory: Directory.Data });

Directory.Data is private to your app and kept until the app is uninstalled. Directory.Cache may be cleared by the system when space is low. Directory.Documents is user visible on some platforms. Store only the file name in your database (see Storage, Preferences and SQLite) and rebuild the path when you need it.

Stand-in: a filesystem in memory

The real plugin needs a device, so here is an in-memory model with the same method names and options. It shows the logic your code needs: recursive folders, base64 data and errors for missing files.

JS An in-memory Filesystem

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Stand-in: the camera permission flow

Here is the decision logic every camera screen needs: check, ask, fall back.

JS A permission-aware takePhoto()

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Showing the photo in the template

Once you have a file URI, convert it and bind it to an image:

HTML
<!-- Ionic Angular -->
<ion-img [src]="photo.src"></ion-img>

ion-img lazy loads, which keeps long lists smooth. Compare with Performance and Lazy Loading.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is CameraResultType.Uri usually better than Base64 for stored photos?

    A URI points at a file, so the web view does not have to hold the whole image as a string.
  2. 2. A user denied the camera twice. What does requestPermissions() do now?

    The system will not show the dialog again, so give the user another path or send them to Settings.
  3. 3. Which directory is private to your app and survives restarts?

    Data is kept until the app is uninstalled, while Cache may be cleared by the system.
  4. 4. What does Capacitor.convertFileSrc() produce?

    File URIs cannot be used directly in img tags; convertFileSrc rewrites them to a web view URL.

Summary

  • Camera returns a photo; prefer Uri over Base64.
  • Check and request permissions at the moment of need and plan a fallback for denial.
  • Filesystem writes into directories such as Data and Cache; store only file names.
  • Convert file URIs with Capacitor.convertFileSrc() before showing them.
  • iOS needs usage descriptions in Info.plist.

Next: Geolocation, Device and Network