i'm trying to download a pdf file from url but i'm getting this error
Error: Download manager failed to download from "myurl" status code=16
i can download the pdf file when i use the same url in chrome
const downloadFile = (FILE_URL) => {
const { config, fs } = RNFetchBlob;
let RootDir = fs.dirs.PictureDir;
let options = {
fileCache: true,
addAndroidDownloads: {
path:
RootDir+
'/file_' +
Math.floor(date.getTime() + date.getSeconds() / 2) +
file_ext,
description: 'downloading file...',
notification: true,
useDownloadManager: true,
},
};
config(options)
.fetch('GET', FILE_URL)
.then(res => {
setDownloading(false)
console.log('res -> ', JSON.stringify(res));
alert('Téléchargement terminé');
});
};
const checkPermission = async (FILE_URL) => {
if (Platform.OS === 'ios') {
downloadFile(FILE_URL);
} else {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
{
title: 'Storage Permission Required',
message:
'Application needs access to your storage to download File',
}
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
downloadFile(FILE_URL);
} else {
Alert.alert('Error','Storage Permission Not Granted');
}
}
}
Related
react native pdf file download after i have not open not for android
working for ios iPhone 13 device IOS 15.5
android Pixels 3a android 11v
i think i have added everything needed in android manifest,
It works for ios devices but not for android. after i download the file i can't open it i.e. there is a download error
my code:
import { Alert, PermissionsAndroid, Platform } from 'react-native';
import RNFetchBlob from 'rn-fetch-blob';
interface IDownloadOptions {
src: string;
fileName: string;
token: string | null;
setLoading?: (loading: boolean) => void;
}
// commint
class DownloadManager {
public download = async (options: IDownloadOptions): Promise<any> => {
const { token, src, fileName, setLoading } = options;
const { dirs } = RNFetchBlob.fs;
const dirToSave = Platform.OS === 'ios' ? dirs.DocumentDir : dirs.DownloadDir;
console.log('dirToSave', dirToSave);
if (Platform.OS === 'android') {
const permission = await PermissionsAndroid.request('android.permission.WRITE_EXTERNAL_STORAGE');
if (permission !== 'granted') {
console.log('not granted');
setLoading && setLoading(false);
return;
}
}
const ios = RNFetchBlob.ios;
const android = RNFetchBlob.android;
const configfb = {
fileCache: true,
useDownloadManager: true,
notification: true,
mediaScannable: true,
title: fileName,
path: `${dirToSave}/${fileName}`,
};
console.log('config', configfb);
return new Promise((resolve, reject) => {
requestAnimationFrame(() => {
RNFetchBlob.config({
fileCache: configfb.fileCache,
// #ts-ignore
title: configfb.title,
path: configfb.path,
// #ts-ignore
appendExt: 'pdf',
addAndroidDownloads: {
...configfb,
},
})
.fetch('GET', src, {
Authorization: `Bearer ${token}`,
})
.then(res => {
const status = res.info().status;
console.log('status: ' + status);
console.log('res: ' + res);
if (status === 200) {
if (Platform.OS === 'ios') {
ios.openDocument(res.data);
}
if (Platform.OS === 'android') {
android.actionViewIntent(res.path(), 'pdf');
}
}
if (status === 500) {
Alert.alert('Server error 500');
}
setLoading && setLoading(false);
resolve(res);
})
.catch(error => {
console.log('error', error);
setLoading && setLoading(false);
reject(error);
});
});
});
};
}
I figured out it is not possible to share video content onto Instagram directly on Android in behalf of the user. This was my original intention.
Seems I can not use navigator.share call which works on iOS but not on Android, or only for text and url, but not for video / mp4.
I would not use MediaStore and similar React Nativ solutions as my app is a regular React.
What elso approach do you know?
I have now this:
const showShareDialog = async () => {
try {
log(
{
text: 'setIsDownloadFileInProgress(true) ' + getTempUserShortId(),
},
env
)
setIsDownloadFileInProgress(true)
const res = await axios.get(
`https://t44-post-cover.s3.eu-central-1.amazonaws.com/${imgId}.mp4`,
{ withCredentials: false, responseType: 'blob' }
)
setIsDownloadFileInProgress(false)
const shareData = {
files: [
new File([res.data], `${imgId}.mp4`, {
type: 'video/mp4',
}),
],
title: 'Megosztom',
text: 'Mentsd le a képekbe, és oszd meg storyban.',
}
//showShareDialog(shareData, 0)
if (navigator.share && !isDesktop) {
log(
{
text:
`navigator.share && !isDesktop shareData.files[0].size: ${shareData.files[0].size} ` +
getTempUserShortId(),
},
env
)
if (isAndroid()) {
const { status } = await MediaLibrary.requestPermissionsAsync()
if (status === 'granted') {
const asset = await MediaLibrary.createAssetAsync(res.data)
await MediaLibrary.createAlbumAsync(`${imgId}.mp4`, asset, false)
}
} else {
navigator
.share(shareData)
.then(() => {
log(
{
text: `'The share was successful 1 ` + getTempUserShortId(),
},
env
)
})
.catch((error) => {
log(
{
text:
`There was an error sharing 1 ${error} ` +
getTempUserShortId(),
},
env
)
})
}
} else {
log(
{
text: 'else ' + getTempUserShortId(),
},
env
)
setIsDesktopDownloadDialogVisible(true)
}
} catch (error) {
console.error(error)
log(
{
text: `a onclick error 2: ${error} ` + getTempUserShortId(),
},
env
)
}
}
I’m downloading a file, and I’ve expected open the file after finished downloading, but this does not work, it’s viewed on a black screen when opening using Linking, and I open this file in the folder where it is and it opens correctly. How can I fix this?
This is the URL of the file in STORAGE:
content://com.android.externalstorage.documents/tree/primary%3ADownload%2FSigaa/document/primary%3ADownload%2FSigaa%2Fhistory.pdf
My code:
const downloadPath = FileSystem.documentDirectory! + (Platform.OS == "android" ? "" : "");
const ensureDirAsync: any = async (dir: any, intermediates = true) => {
const props = await FileSystem.getInfoAsync(dir);
if (props.exists && props.isDirectory) {
return props;
}
let _ = await FileSystem.makeDirectoryAsync(dir, { intermediates });
return await ensureDirAsync(dir, intermediates);
};
const downloadFile = async (fileUrl) => {
if (Platform.OS == "android") {
const dir = ensureDirAsync(downloadPath);
}
let fileName = "history";
const downloadResumable = FileSystem.createDownloadResumable(
fileUrl,
downloadPath + fileName,
{}
);
console.log(downloadPath);
try {
const { uri } = await downloadResumable.downloadAsync();
saveAndroidFile(uri, fileName);
} catch (e) {
console.error("download error:", e);
}
};
const saveAndroidFile = async (fileUri, fileName = "File") => {
try {
const fileString = await FileSystem.readAsStringAsync(fileUri, { encoding: FileSystem.EncodingType.Base64 });
if (local === "") {
const permissions = await StorageAccessFramework.requestDirectoryPermissionsAsync();
if (!permissions.granted) {
return;
}
await AsyncStorage.setItem("local", permissions.directoryUri);
}
try {
await StorageAccessFramework.createFileAsync(local, fileName, "application/pdf")
.then(async (uri) => {
await FileSystem.writeAsStringAsync(uri, fileString, { encoding: FileSystem.EncodingType.Base64 });
Linking.openURL(uri);
alert("Success!");
})
.catch((e) => {});
} catch (e) {
throw new Error(e);
}
} catch (err) {}
};
The black screen when opening:
I solved this by implementing the intent launcher api for android and the sharing api for ios.
To make it work it is important to provide the mimeType of the file (or UTI for IOS). You can extract it manually from the file extension but there's a library for that on RN: react-native-mime-types.
Actually I think any library that doesn't deppend on node core apis shoud work just fine.
Here's the code:
const openFile = async (fileUri: string, type: string) => {
try {
if (Platform.OS === 'android') {
await startActivityAsync('android.intent.action.VIEW', {
data: fileUri,
flags: 1,
type,
});
} else {
await shareAsync(fileUri, {
UTI: type,
mimeType: type,
});
}
} catch (error) {
// do something with error
}
};
I need to download file to user's Download directory in React Native app using rn-fetch-blob, but seems like it is not compatible with Android 10, because I am getting error:
First I ask for permissions:
try {
const granted = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
await actualDownloadPDF();
} else {
ToastAndroid.show('Nepovolili jste ukládání souborů do zařízení.', ToastAndroid.LONG);
}
} catch (err) {
console.warn(err);
}
then I try to download file:
const res = await RNFetchBlob.config({
addAndroidDownloads: {
useDownloadManager: true,
notification: true,
mime: 'application/pdf',
title: filename,
path: dirs.DownloadDir,
},
}).fetch('GET', url, {
Authorization: 'Bearer ' + Api.Bearer,
});
It seems like Android 10 requires from developer to open Intent where user select write permission to folder (
https://developer.android.com/training/data-storage/shared/documents-files#grant-access-directory), but I am not sure how to do it, because it seems like RNFetchBlob does not have this feature, yet.
Any ideas how to make this work? It was working fine on Android 9.
const fileName = 'document.pdf';
const destPath = RNFetchBlob.fs.dirs.DownloadDir + '/' + fileName;
const config = {
fileCache : true,
path: destPath,
addAndroidDownloads: {
title: destPath,
description: `Download ${destPath}`,
useDownloadManager: false,
notification: false,
}
};
const res = await RNFetchBlob.config(config)...
I'm using this code and it works on Android 10.
I think that your if clause is wrong. My working example look like this:
import { PermissionsAndroid } from "react-native";
export const CheckFilePermissions = async (platform) => {
if(platform === 'android') {
try {
const granted = await PermissionsAndroid.requestMultiple([
PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
]);
if (granted['android.permission.READ_EXTERNAL_STORAGE'] && granted['android.permission.WRITE_EXTERNAL_STORAGE']) {
// user granted permissions
return true;
} else {
// user didn't grant permission... handle with toastr, popup, something...
return false;
}
} catch (err) {
// unexpected error
return false;
}
} else {
// platform is iOS
return true;
}
};
You can use it like:
if(await CheckFilePermissions(Platform.OS)) {
....
your code
....
Add android:requestLegacyExternalStorage="true" to in your AndroidManifest.xml
<application
...
android:requestLegacyExternalStorage="true"
>
You should give complete path to the 'path' field.
Change
path: dirs.DownloadDir
to
path: dirs.DownloadDir`/download.pdf`
I'm using the following code to download a file (can be a PDF or a DOC) and then opening it using Linking.
const { dirs } = RNFetchBlob.fs;
let config = {
fileCache : true,
appendExt : extension,
addAndroidDownloads : {
useDownloadManager : false,
notification : false,
title : 'File',
description : 'A file.',
path: `${dirs.DownloadDir}/file.${extension}`,
},
};
RNFetchBlob.config(config)
.fetch(
method,
remoteUrl,
APIHelpers.getDefaultHeaders()
)
.then((res) => {
let status = res.info().status;
if (status == 200) {
Linking.canOpenURL(res.path())
.then((supported) => {
if (!supported) {
alert('Can\'t handle url: ' + res.path());
} else {
Linking.openURL(res.path())
.catch((err) => alert('An error occurred while opening the file. ' + err));
}
})
.catch((err) => alert('The file cannot be opened. ' + err));
} else {
alert('File was not found.')
}
})
.catch((errorMessage, statusCode) => {
alert('There was some error while downloading the file. ' + errorMessage);
});
However, I'm getting the following error:
An error occurred while opening the file. Error: Unable to open URL:
file:///Users/abhishekpokhriyal/Library/Developer/CoreSimulator/Devices/3E2A9C16-0222-40A6-8C1C-EC174B6EE9E8/data/Containers/Data/Application/A37B9D69-583D-4DC8-94B2-0F4AF8272310/Documents/RNFetchBlob_tmp/RNFetchBlobTmp_o259xexg7axbwq3fh6f4.pdf
I need to implement the solution for both iOS and Android.
I think the easiest way to do so is by using react-native-file-viewer package.
It allows you to Prompt the user to choose an app to open the file with (if there are multiple installed apps that support the mimetype).
import FileViewer from 'react-native-file-viewer';
const path = // absolute-path-to-my-local-file.
FileViewer.open(path, { showOpenWithDialog: true })
.then(() => {
// success
})
.catch(error => {
// error
});
So, I finally did this by replacing Linking by the package react-native-file-viewer.
In my APIHelpers.js:
async getRemoteFile(filePath, extension, method = 'GET') {
const remoteUrl = `${API_BASE_URL}/${encodeURIComponent(filePath)}`;
const { dirs } = RNFetchBlob.fs;
let config = {
fileCache : true,
appendExt : extension,
addAndroidDownloads : {
useDownloadManager : false,
notification : false,
title : 'File',
description : 'A file.',
path: `${dirs.DownloadDir}/file.${extension}`,
},
};
return new Promise(async (next, error) => {
try {
let response = await RNFetchBlob.config(config)
.fetch(
method,
remoteUrl,
this.getDefaultHeaders()
);
next(response);
} catch (err) {
error(err);
}
});
}
In my Actions.js
export function openDocument(docPath, ext) {
return async (dispatch) => {
dispatch(fetchingFile());
APIHelpers.getRemoteFile(docPath, ext).then(async function(response) {
dispatch(successFetchingFile());
let status = response.info().status;
if (status == 200) {
const path = response.path();
setTimeout(() => {
FileViewer.open(path, {
showOpenWithDialog: true,
showAppsSuggestions: true,
})
.catch(error => {
dispatch(errorOpeningFile(error));
});
}, 100);
} else {
dispatch(invalidFile());
}
}).catch(function(err) {
dispatch(errorFetchingFile(err));
});
}
}
In my Screen.js
import { openDocument } from 'path/to/Actions';
render() {
return <Button
title={'View file'}
onPress={() => this.props.dispatchOpenDocument(doc.filepath, doc.extension)}
/>;
}
.
.
.
const mapDispatchToProps = {
dispatchOpenDocument: (docPath, ext) => openDocument(docPath, ext),
}
Are you downloading it from the web? I can see the pdf path is attached at the end of the error path.
For web URLs, the protocol ("http://", "https://") must be set accordingly!
Try to append appropriate schemes to your path. Check it out from the link mentioned below.
This can be done with 'rn-fetch-blob'
RNFetchBlob.android.actionViewIntent(fileLocation, mimeType);