React Native Expo: Save File to Device in Given Folder
Currently, there is no easy solution and feature or
trick or tutorial how to write files on internal storage and that is very tedious
work to save find on the given provided folder and app directory with expo without detaching
I want to save files on internal storage like Downloads,
WhatsApp, DCIM, Pictures
This feature useful for the app with download files/picture/music feature.
In this working tutorial, we are going to download video files from the server and the same file will be moved to the desire device folder.
Here are steps that you need to do, This is working code in ANDROID and that should work on iOs as well.
You need to install following expo packages expo-media-library, expo-permissions and expo-file-system
- Permissions.CAMERA_ROLL Permission is required, that should be fine.
- Using FileSystem to download video, it will provide local URI from device
- After call saveFile method to move the file to the desired folder.
import * as MediaLibrary from 'expo-media-library';
import * as Permissions from 'expo-permissions';
const saveFile = async (fileUri) => {
const { status } = await Permissions.askAsync(Permissions.CAMERA_ROLL);
if (status === 'granted') {
const asset = await MediaLibrary.createAssetAsync(fileUri);
await MediaLibrary.createAlbumAsync('<FOLDER NAME>', asset, false);
}
};
let lastIndex = media?.uri.lastIndexOf('/');
let fileName = media?.uri.substring(lastIndex);
let downloadResumable = FileSystem.createDownloadResumable(
"http://d23dyxeqlo5psv.cloudfront.net/big_buck_bunny.mp4",
FileSystem.documentDirectory + fileName,
{},
() => {
// down progress monitor here
}
);
try {
const { uri } = await downloadResumable.downloadAsync().then((item) => {
return item;
});
await saveFile(uri)
.then((rs) => {
alert('Video saved to download
folder);
});
} catch (e) {
console.error(e);
}
};
Comments
Post a Comment