I am trying to download a pdf from the URL. I am using RNFetchBlob to download pdf from URLs. It is also getting downloaded successfully. But it doesn't open. It says invalid format. At first, I thought it might be because I was running in an emulator but I tried on a real device also it is also giving an invalid format.
Below is the code I am using:
const downloadFile = async (url, title) => {
const grantedstorage = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE);
if (grantedstorage === PermissionsAndroid.RESULTS.GRANTED) {
const { dirs } = RNFetchBlob.fs;
const dirToSave = Platform.OS == 'ios' ? dirs.DocumentDir : dirs.DownloadDir
const configfb = {
fileCache: true,
addAndroidDownloads: {
useDownloadManager: true,
notification: true,
mediaScannable: true,
title: title + ".pdf",
path: dirToSave + "/" + title + ".pdf",
mime : 'application/pdf',
}
}
const configOptions = Platform.select({
ios: {
fileCache: configfb.fileCache,
title: configfb.title,
path: configfb.path,
appendExt: 'pdf',
notification: configfb.notification
},
android: configfb,
});
RNFetchBlob.config(configOptions)
.fetch('GET', url,{})
.then((res) => {
if (Platform.OS === "ios") {
RNFetchBlob.fs.writeFile(configfb.path, res.data, 'base64');
RNFetchBlob.ios.previewDocument(configfb.path);
}
if (Platform.OS == 'android') {
alert('File downloaded');
}
console.log('The file saved to ', res.path());
})
.catch((e) => {
console.log('Catch ERROR', e.message)
});
} else if (grantedstorage === PermissionsAndroid.RESULTS.DENIED) {
alert("Please allow permission to storage if you want to download file.");
}
else {
alert("Please go to app setting and allow permission to storage.");
}
}
Please help me solve this. And yes the URL is of a protected pdf if that is of any concern, please let me know.