3d cartoon hands holding a phone

Unlock full course by purchasing a membership

Lesson 5

Use the Native Filesystem to Store Photos

Using the Filesystem API

STANDARD

Use the Native Filesystem to Store Photos

In the previous lesson, we already started implementing a way to trigger different behaviour depending on whether the application is running on the web or natively on iOS/Android.

Our ultimate goal here is to use simple data URLs for photos while testing on the web/desktop, but when we are running the application on iOS/Android we want to use actual files stored on the device. More specifically, we also want to make sure to move those photo files to permanent storage on the users device. That is what we are going to be tackling in this lesson.

This lesson will only be relevant if you are running your application natively on iOS/Android. However, even if you don’t intend to run this application natively right now, you can still add this code to your application. Remember, one of the key benefits of Ionic/Capacitor is that we can run the same code on multiple platforms, and we aren’t going to break our web code by adding this functionality.

Let’s get started.

Configuring the Filesystem plugin:

Install the Filesystem plugin:

npm install @capacitor/filesystem
npx cap sync

As with the Camera plugin, this plugin also requires native configuration which you can find here. However, if you have already performed the configuration for the Camera plugin then you should already have the permissions required for the Filesystem plugin.

Moving Files to Permanent Storage

We already have the basic structure of our takePhoto method in our PhotoService which currently looks like this:

  async takePhoto() {
    const options: ImageOptions = {
      quality: 50,
      width: 600,
      allowEditing: false,
      resultType: this.platform.is('capacitor')
        ? CameraResultType.Uri
        : CameraResultType.DataUrl,
      source: CameraSource.Camera,
    };

    try {
      const photo = await Camera.getPhoto(options);

      if (photo.path) {
        this.addPhoto(Date.now().toString(), photo.path);
      } else if (photo.dataUrl) {
        this.addPhoto(Date.now().toString(), photo.dataUrl);
      }
    } catch (err) {
      console.log(err);
      throw new Error('Could not save photo');
    }
  }

We are already implementing two sets of behaviours based on whether the application is running natively or not:

STANDARD
Key

Thanks for checking out the preview of this lesson!

You do not have the appropriate membership to view the full lesson. If you would like full access to this module you can view membership options (or log in if you are already have an appropriate membership).