Skip to main content

将照片保存到文件系统

¥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 lost.

文件系统 API

¥Filesystem API

幸运的是,将它们保存到文件系统只需几个步骤。首先打开 usePhotoGallery 功能 (src/composables/usePhotoGallery.ts)。

¥Fortunately, saving them to the filesystem only takes a few steps. Begin by opening the usePhotoGallery function (src/composables/usePhotoGallery.ts).

文件系统 API 要求将写入磁盘的文件作为 base64 数据传入,因此稍后将使用此辅助函数来协助完成此操作:

¥The Filesystem API requires that files written to disk are passed in as base64 data, so this helper function will be used in a moment to assist with that:

const convertBlobToBase64 = (blob: Blob) =>
new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onerror = reject;
reader.onload = () => {
resolve(reader.result);
};
reader.readAsDataURL(blob);
});

接下来,添加一个将照片保存到文件系统的功能。我们传入 photo 对象,它代表新捕获的设备照片,以及 fileName,它将提供文件的存储路径。

¥Next, add a function to save the photo to the filesystem. We pass in the photo object, which represents the newly captured device photo, as well as the fileName, which will provide a path for the file to be stored to.

接下来我们使用 Capacitor 文件系统 API 将照片保存到文件系统。我们首先将照片转换为 base64 格式,然后将数据提供给文件系统的 writeFile 函数:

¥Next we use the Capacitor Filesystem API to save the photo to the filesystem. We start by converting the photo to base64 format, then feed the data to the Filesystem’s writeFile function:

const savePicture = async (photo: Photo, fileName: string): Promise<UserPhoto> => {
// Fetch the photo, read as a blob, then convert to base64 format
const response = await fetch(photo.webPath!);
const blob = await response.blob();
const base64Data = (await convertBlobToBase64(blob)) as string;

const savedFile = await Filesystem.writeFile({
path: fileName,
data: base64Data,
directory: Directory.Data,
});

// Use webPath to display the new image instead of base64 since it's
// already loaded into memory
return {
filepath: fileName,
webviewPath: photo.webPath,
};
};

最后,更新 takePhoto 函数以调用 savePicture。保存照片后,将其插入反应式 photos 数组的前面:

¥Last, update the takePhoto function to call savePicture. Once the photo has been saved, insert it into the front of reactive photos array:

const takePhoto = async () => {
const photo = await Camera.getPhoto({
resultType: CameraResultType.Uri,
source: CameraSource.Camera,
quality: 100,
});

const fileName = Date.now() + '.jpeg';
const savedFileImage = await savePicture(photo, fileName);

photos.value = [savedFileImage, ...photos.value];
};

我们开始吧!每次拍摄新照片时,它都会自动保存到文件系统中。

¥There we go! Each time a new photo is taken, it’s now automatically saved to the filesystem.