將照片儲存到檔案系統
我們現在能夠拍攝多張照片,並將它們顯示在應用程式第二個標籤頁的照片庫中。然而,這些照片目前並未永久儲存,因此當應用程式關閉時,它們將會遺失。
檔案系統 API
幸運的是,將它們儲存到檔案系統只需幾個步驟。首先開啟 usePhotoGallery
鉤子 (src/hooks/usePhotoGallery.ts
),並取得 Filesystem
類別的 writeFile
方法的存取權。
注意
我們最初將使用 writeFile
方法,但我們很快就會使用其他方法,所以我們現在就先將它們匯入。
接下來,在 usePhotoGallery
中建立幾個新函式。
export function usePhotoGallery() {
const savePicture = async (photo: Photo, fileName: string): Promise<UserPhoto> => {
const base64Data = await base64FromPath(photo.webPath!);
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,
};
};
}
export async function base64FromPath(path: string): Promise<string> {
const response = await fetch(path);
const blob = await response.blob();
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onerror = reject;
reader.onload = () => {
if (typeof reader.result === 'string') {
resolve(reader.result);
} else {
reject('method did not return a string');
}
};
reader.readAsDataURL(blob);
});
}
注意
base64FromPath 方法是一個輔助工具,它會從提供的路徑下載檔案,並傳回該檔案的 base64 表示法。
我們傳入 photo
物件,它代表新拍攝的裝置照片,以及 fileName,它將提供儲存檔案的路徑。
接下來,我們使用 Capacitor Filesystem API 將照片儲存到檔案系統。我們先將照片轉換為 base64 格式,然後將資料饋送到 Filesystem 的 writeFile
函式。
最後,在 takePhoto
方法中呼叫 setPhotos
後立即呼叫 savePicture
並傳入照片物件和檔案名稱。以下是完整的方法
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);
const newPhotos = [savedFileImage, ...photos];
setPhotos(newPhotos);
};
完成了!每次拍攝新照片時,它現在都會自動儲存到檔案系統。