In my React Native Expo project, I am utilizing two functions to store data in a JSON file and then save the file to internal storage. However, the code currently asks for permission to store inside a chosen folder, but does not create the "ProjectName" folder before creating the file. Despite trying various methods, I have been unable to achieve the desired outcome of creating the folder first and then saving the file within it. Can anyone provide insight on how to accomplish this?
Here are the two functions that I have attempted:
const saveJSONToFile = async (fileName, jsonData, mimetype) => {
const directory = FileSystem.documentDirectory + 'my-project/';
const fileUri = directory + fileName + '.json';
try {
await FileSystem.makeDirectoryAsync(directory, { intermediates: true });
await FileSystem.writeAsStringAsync(fileUri, JSON.stringify(jsonData));
console.log('File URI:', fileUri);
} catch (error) {
console.error('Error saving JSON data:', error);
}
await saveFile(fileUri, fileName, mimetype);
};
const saveFile = async (uri, filename, mimetype) => {
if (Platform.OS === "android") {
const permissions = await FileSystem.StorageAccessFramework.requestDirectoryPermissionsAsync();
if (permissions.granted) {
const base64 = await FileSystem.readAsStringAsync(uri, { encoding: FileSystem.EncodingType.Base64 });
await FileSystem.StorageAccessFramework.createFileAsync(permissions.directoryUri+'/ProjectName/', filename, mimetype)
.then(async (uri) => {
await FileSystem.writeAsStringAsync(uri, base64, { encoding: FileSystem.EncodingType.Base64 });
})
.catch(e => console.log(e));
} else {
await shareAsync(uri);
}
} else {
await shareAsync(uri);
}
};