Skip to content

Instantly share code, notes, and snippets.

@biancadragomir
Last active March 25, 2021 13:17
Show Gist options
  • Save biancadragomir/943acd3bf949d76d07831b9db158fe9a to your computer and use it in GitHub Desktop.
Save biancadragomir/943acd3bf949d76d07831b9db158fe9a to your computer and use it in GitHub Desktop.
export const downloadFile = async (file: GenericFile) => {
const signalError = () => {
showMessage(i18n.t('file_download_failed'), colors.RED);
};
const signalSuccess = () => {
showMessage(i18n.t('file_download_success'), colors.GREEN);
};
const downloadUrl = await buildDownloadUrl(file);
try {
const {
dirs: { DownloadDir, DocumentDir },
} = RNFetchBlob.fs;
const isIOS = Platform.OS === 'ios';
const directoryPath = Platform.select({
ios: DocumentDir,
android: DownloadDir,
});
const filePath = `${directoryPath}/${file.name}`;
const fileExt = file.ext;
var mimeType = '';
if (fileExt === 'png' || fileExt === 'jpg' || fileExt === 'jpeg') {
mimeType = 'image/*';
}
if (fileExt === 'pdf') {
mimeType = 'application/pdf';
}
if (fileExt === 'avi' || fileExt === 'mp4' || fileExt === 'mov') {
mimeType = 'video/*';
}
const configOptions = Platform.select({
ios: {
fileCache: true,
path: filePath,
appendExt: fileExt,
notification: true,
},
android: {
fileCache: true,
appendExt: fileExt,
addAndroidDownloads: {
useDownloadManager: true,
mime: mimeType,
title: file.name,
mediaScannable: true,
notification: true,
},
},
});
RNFetchBlob.config(configOptions as RNFetchBlobConfig)
.fetch('GET', downloadUrl)
.then((resp) => {
console.log(resp);
signalSuccess();
if (isIOS) {
RNFetchBlob.ios.openDocument(resp.data);
}
})
.catch((e) => {
signalError();
console.log('fetch error: ', e);
});
} catch (error) {
console.log('general error: ', error);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment