How to create .DOC file witih expo-file-system? - react-native

I just created a similar question regarding promises...
But I'm having trouble saving .DOC files.
It comes corrupted when saving:
Could not get the file's extension.
and is being saved in:
file:///storage/emulated/0/DCIM/2021-09-01_5.doc
How to fix it?
data.map(async (index) => {
const date = new Date(index.synchronization)
const formattedDate = date.toISOString().split('T')[0];
const fileUri = `${FileSystem.documentDirectory}${formattedDate}.doc`;
await FileSystem.writeAsStringAsync(
fileUri,
"Hello World, i'am saving this file :)").then(response => console.log(response)).catch(error => console.log(error));
const { uri } = await MediaLibrary
.createAssetAsync(`${fileUri}`)
.then((response) => console.log(response))
.catch((error) => error);
console.log(uri)
await MediaLibrary.createAssetAsync("Downloads", uri).then(response => console.log(response)).catch(error => console.log(error.message));
});

Related

How to save .DOC file with expo-file-system in react-native?

I'm having trouble saving a .DOC file using expo-file-system.
I'm getting the following feedback:
[Unhandled promise rejection: Error: Invalid argument "localUri". It
must be a string!]
This is my current code:
useEffect(() => {
const saveFile = async () => {
const { granted } = await Notifications
.requestPermissionsAsync()
.then((response) => response)
.catch((error) => error);
console.log(granted);
if (granted) {
data.map(async (index) => {
const date = new Date(index.synchronization)
const formattedDate = date.toISOString().split('T')[0];
const fileUri = `${FileSystem.documentDirectory}${formattedDate}.doc`;
console.log(fileUri)
await FileSystem.writeAsStringAsync(
fileUri,
"Hello World, i'am saving this file :)",
{
encoding: FileSystem.EncodingType.UTF8
});
const asset = await MediaLibrary.createAssetAsync(`${fileUri}`);
await MediaLibrary.createAssetAsync(asset);
console.log(asset);
});
}
}
saveFile();
}, [data]);
The error is probably occurring on this line:
const asset = await MediaLibrary.createAssetAsync(`${fileUri}`);
await MediaLibrary.createAssetAsync(asset);
Okay, I did!
It's a boring prank these promises
const { uri } = await MediaLibrary
.createAssetAsync(`${fileUri}`)
.then((response) => response)
.catch((error) => error);;
await MediaLibrary.createAssetAsync(uri);
Necessita do uso de then and catch

can't play this file error using react-native-expo

I want to play a video but i face the can't play this video file error
When I try it with this link, the video is properly downloaded and also played but with this link, it says the video file is corrupt.
const downloadFile = () => {
const uri = "instagram.com/p/CET9SzMpCYg/?utm_source=ig_web_copy_link"
let fileUri = FileSystem.documentDirectory +"video.mp4";
FileSystem.downloadAsync(uri,fileUri)
.then(({ uri }) => { saveFile(uri); })
.catch(error => { console.error(error); })
}
const saveFile = async fileUri => {
const { status } = await Permissions.askAsync(Permissions.CAMERA_ROLL);
if (status === "granted") {
const asset = await MediaLibrary.createAssetAsync(fileUri);
await MediaLibrary.createAlbumAsync("Download", asset, false);
alert('Saved to Downloads');
}
}

How to save image to Document Directory from local file in react native?

I am new to react native, I want to save an image from local folder(like Module/assets/ImageName.png) in my project into Document Directory. I am using the 'react-native-fs' library for the same.
Code is below:
componentWillMount() {
var RNFS = require('react-native-fs');
var path = RNFS.DocumentDirectoryPath + '/ImageName.png';
// write the file
RNFS.writeFile(path, './Module/assets/ImageName.png', 'utf8') // what to use inplace of utf8?
.then((success) => {
console.log(path);
})
.catch((err) => {
console.log(err.message);
});
}
Please suggest how should I proceed?
Thanks.
For images included via Xcode asset catalogs use the image name without the extension:
var path = RNFS.DocumentDirectoryPath + '/ImageName.png';
RNFS.copyAssetsFileIOS('ImageName.png', path, 100, 100)
.then(results => {
console.log('Copy File', results);
})
.catch(err => {
console.log('Error copying file', err);
});

remove downloaded image by react native fetch blob?

I am using RNFetchBlob to share image as base64 format. But the image is downloading in my local folder. I want to delete it. By my research knowledge i want to unlink the image path. I don't know how to do that. Here is my code
_downloadImageAndShare(url ,title, message) {
const { fs } = RNFetchBlob.fs;
const self = this;
RNFetchBlob.config({ fileCache: true })
.fetch('GET', url)
.then(resp => resp.readFile('base64')
.then(base64 => ({ resp, base64 })))
.then(obj => {
const headers = obj.resp.respInfo.headers;
const type = headers['Content-Type'];
const dataUrl = 'data:' + type + ';base64,' + obj.base64;
return { url: dataUrl, title, message };
})
.then(options => Share.open(options)).catch(err => {err &&
console.log(err); })
}
how to use this code inside this method
RNFetchBlob.fs.unlink(path)
.then(() => { ... })
.catch((err) => { ... })
and how to specify the unlink(path) ??
thanks in advance.
You can specify file location with config with path param.
const filePath = RNFetchBlob.fs.dirs.DocumentDir + '/myFile';
RNFetchBlob.config({ fileCache: true, path : filePath })
.fetch('GET', url)
.then(resp => resp.readFile('base64')
.then(base64 => ({ resp, base64 })))
.then(obj => {
const headers = obj.resp.respInfo.headers;
const type = headers['Content-Type'];
const dataUrl = 'data:' + type + ';base64,' + obj.base64;
return { url: dataUrl, title, message };
})
.then(options => Share.open(options)).catch(err => {err &&
console.log(err); })
}
Then you can call unlink like this
RNFetchBlob.fs.unlink(filePath)
.then(() => { ... })
.catch((err) => { ... })

how to implement cache in react-native-video

How do we implement caching in react-native-video? Basically, when a video is currently streaming from a network resource, how do we save the video somewhere, and then retrieve it when the same resource is access. What is the best approach for this?
The best approach that i would refer you is using react-native-fetch-blob, you can implement it like this:
const RNFetchBlob = require('react-native-fetch-blob').default;
const {
fs
} = RNFetchBlob;
const baseCacheDir = fs.dirs.CacheDir + '/videocache';
//call the downloadVideo function
downloadVideo('http://....',baseCacheDir)
//Function to download a file..
const activeDownloads = {};
function downloadVideo(fromUrl, toFile) {
// use toFile as the key
activeDownloads[toFile] = new Promise((resolve, reject) => {
RNFetchBlob
.config({path: toFile})
.fetch('GET', fromUrl)
.then(res => {
if (Math.floor(res.respInfo.status / 100) !== 2) {
throw new Error('Failed to successfully download video');
}
resolve(toFile);
})
.catch(err => {
return deleteFile(toFile)
.then(() => reject(err));
})
.finally(() => {
// cleanup
delete activeDownloads[toFile];
});
});
return activeDownloads[toFile];
}
//To delete a file..
function deleteFile(filePath) {
return fs.stat(filePath)
.then(res => res && res.type === 'file')
.then(exists => exists && fs.unlink(filePath)) //if file exist
.catch((err) => {
// swallow error to always resolve
});
}
Cheers:)