跳到主要內容
版本:v8

將照片儲存到檔案系統

我們現在可以拍攝多張照片,並在應用程式第二個標籤上的照片庫中顯示它們。然而,這些照片目前並未永久儲存,因此當應用程式關閉時,它們將會遺失。

檔案系統 API

幸運的是,將它們儲存到檔案系統只需要幾個步驟。首先開啟 usePhotoGallery 函式 (src/composables/usePhotoGallery.ts)。

檔案系統 API 要求寫入磁碟的檔案以 base64 資料傳遞,因此稍後會使用這個輔助函式來協助

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。

接下來,我們使用 Capacitor 檔案系統 API 將照片儲存到檔案系統。我們先將照片轉換為 base64 格式,然後將資料饋送到檔案系統的 writeFile 函式

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 陣列的前面

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];
};

完成!每次拍攝新照片時,它現在都會自動儲存到檔案系統。