Saving Photos to the Filesystem
We’re now able to take multiple photos and display them in a photo gallery on the second tab of our app. These photos, however, are not currently being stored permanently, so when the app is closed, they will be deleted.
#
Filesystem APIFortunately, saving them to the filesystem only takes a few steps. Begin by creating a new class method, savePicture()
, in the PhotoService
class (src/app/services/photo.service.ts
). We pass in the cameraPhoto
object, which represents the newly captured device photo:
We can use this new method immediately in addNewToGallery()
:
We’ll use the Capacitor Filesystem API to save the photo to the filesystem. To start, convert the photo to base64 format, then feed the data to the Filesystem’s writeFile
function. As you’ll recall, we display each photo on the screen by setting each image’s source path (src
attribute) in tab2.page.html
to the webviewPath property. So, set it then return the new Photo object.
readAsBase64()
is a helper function we’ll define next. It's useful to organize via a separate method since it requires a small amount of platform-specific (web vs. mobile) logic - more on that in a bit. For now, implement the logic for running on the web:
Obtaining the camera photo as base64 format on the web appears to be a bit trickier than on mobile. In reality, we’re just using built-in web APIs: fetch() as a neat way to read the file into blob format, then FileReader’s readAsDataURL() to convert the photo blob to base64.
There we go! Each time a new photo is taken, it’s now automatically saved to the filesystem.