RN fetch blob загрузить docx или pdf из URL-адреса в IOS
Что сделано:
Реализован в Android и его загрузка в конкретных DCIM directory
в android. В iOS с использованиемDocumentDir
чтобы скачать файл в формате pdf или docx. С помощью "rn-fetch-blob": "^0.12.0"
;
Ошибка:
В IOS в консоли отображается сообщение:
Файл сохранен в /var/mobile/Containers/Data/Application/E6FDC2DD-7FCA-44DC-85C4-A275078F8825/Documents/wow13.pdf
Код для загрузки выглядит примерно так:
downloadFileOnSuccess = async () => {
let dirs =
Platform.OS == 'ios'
? RNFetchBlob.fs.dirs.DocumentDir
: RNFetchBlob.fs.dirs.DCIMDir;
console.log(dirs, 'document path');
RNFetchBlob.config({
// response data will be saved to this path if it has access right.
fileCache: true,
path: dirs + `/wow13.pdf`,
})
.fetch(
'GET',
'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf',
{
//some headers ..
},
)
.then(res => {
// the path should be dirs.DocumentDir + 'path-to-file.anything'
console.log('The file saved to ', res.path());
});
};
Но я не могу найти, где файл загружен на моем реальном устройстве iphone 7. Есть ли какое-то разрешение, которое мне не хватает в IOS? Не добавляли никаких разрешений для IOS.
6 ответов
Благодаря pruthvi я получил ответ, для ios мне нужно подсказать пользователю:
.then(resp => {
// console.log(resp);
if (Platform.OS === "ios") {
RNFetchBlob.ios.openDocument(resp.data);
}
})
надеюсь, это поможет вам, ребята
Последнее рабочее решение:
const actualDownload = () => {
const { dirs } = RNFetchBlob.fs;
const dirToSave = Platform.OS == 'ios' ? dirs.DocumentDir : dirs.DownloadDir
const configfb = {
fileCache: true,
useDownloadManager: true,
notification: true,
mediaScannable: true,
title: pdfInfo.pdf,
path: `${dirToSave}/${pdfInfo.pdf}`,
}
const configOptions = Platform.select({
ios: {
fileCache: configfb.fileCache,
title: configfb.title,
path: configfb.path,
appendExt: 'pdf',
},
android: configfb,
});
console.log('The file saved to 23233', configfb, dirs);
RNFetchBlob.config(configOptions)
.fetch('GET', `https://aquatherm.s3.ap-south-1.amazonaws.com/pdfs/${pdfInfo.pdf}`, {})
.then((res) => {
if (Platform.OS === "ios") {
RNFetchBlob.fs.writeFile(configfb.path, res.data, 'base64');
RNFetchBlob.ios.previewDocument(configfb.path);
}
setisdownloaded(false)
if (Platform.OS == 'android') {
showSnackbar('File downloaded');
}
console.log('The file saved to ', res);
})
.catch((e) => {
setisdownloaded(true)
showSnackbar(e.message);
console.log('The file saved to ERROR', e.message)
});
}
Импровизация по ответу Аджмалла Хасана. Мне нужно изменить ${pdfInfo.pdf} на ${'pdfInfo.pdf'}, чтобы он работал
const actualDownload = () => {
const { dirs } = RNFetchBlob.fs;
const dirToSave = Platform.OS == 'ios' ? dirs.DocumentDir : dirs.DownloadDir
const configfb = {
fileCache: true,
useDownloadManager: true,
notification: true,
mediaScannable: true,
title: pdfInfo.pdf,
path: `${dirToSave}/${'pdfInfo.pdf'}`,
}
const configOptions = Platform.select({
ios: {
fileCache: configfb.fileCache,
title: configfb.title,
path: configfb.path,
appendExt: 'pdf',
},
android: configfb,
});
console.log('The file saved to ', configfb, dirs);
RNFetchBlob.config(configOptions)
.fetch('GET', `https://aquatherm.s3.ap-south-1.amazonaws.com/pdfs/${'pdfInfo.pdf'}`, {})
.then((res) => {
if (Platform.OS === "ios") {
RNFetchBlob.fs.writeFile(configfb.path, res.data, 'base64');
RNFetchBlob.ios.previewDocument(configfb.path);
}
if (Platform.OS == 'android') {
showSnackbar('File downloaded');
}
console.log('The file saved to ', res);
})
.catch((e) => {
showSnackbar(e.message);
console.log('The file saved to ERROR', e.message)
});
}
У меня работало, используя собственный ответ
const downloadFile = (fileName) => {
const source = "sample.pdf";
const { dirs } = RNFetchBlob.fs;
RNFetchBlob.config({
fileCache: true,
appendExt: 'pdf',
path: `${dirs.DocumentDir}/${fileName}`,
addAndroidDownloads: {
useDownloadManager: true,
notification: true,
title: fileName,
description: 'File downloaded by download manager.',
mime: 'application/pdf',
},
})
.fetch('GET', source)
.then((res) => {
// in iOS, we want to save our files by opening up the saveToFiles bottom sheet action.
// whereas in Android, the download manager is handling the download for us.
if (Platform.OS === 'ios') {
const filePath = res.path();
let options = {
type: 'application/pdf',
url: filePath,
saveToFiles: true,
};
Share.open(options)
.then((resp) => console.log(resp))
.catch((err) => console.log(err));
}
})
.catch((err) => console.log('BLOB ERROR -> ', err));
};
GetItem_downloadbtn = (item, itemname) => {
var pdfInfo = itemname;
const { dirs } = RNFetchBlob.fs;
const dirToSave = Platform.OS == 'ios' ? dirs.DocumentDir : dirs.DownloadDir
const configfb = {
fileCache: true,
useDownloadManager: true,
notification: true,
mediaScannable: true,
title: pdfInfo.pdf,
path: `${dirToSave}/${itemname}`,
}
const configOptions = Platform.select({
ios: {
fileCache: configfb.fileCache,
title: configfb.title,
path: configfb.path,
appendExt: 'pdf',
},
android: configfb,
});
console.log('The file saved to 23233', configfb, dirs);
RNFetchBlob.config(configOptions)
.fetch('GET', item, {})
.then((res) => {
if (Platform.OS === "ios") {
RNFetchBlob.fs.writeFile(configfb.path, res.data, 'base64');
RNFetchBlob.ios.previewDocument(configfb.path);
}
setisdownloaded(false)
if (Platform.OS == 'android') {
showSnackbar('File downloaded');
}
console.log('The file saved to ', res);
})
.catch((e) => {
setisdownloaded(true)
showSnackbar(e.message);
console.log('The file saved to ERROR', e.message)
});
}
Я использовал это в своем файле. Я использовал код, чтобы поделиться файлом, и он работает, загрузите его из опции «Сохранить в файл».
onClickFileDownload = async () => {
const saveDir = Platform.OS == 'ios' ? `${RNFetchBlob.fs.dirs.DocumentDir}` : `${RNFetchBlob.fs.dirs.DownloadDir}`;
const configfb = {
fileCache: true,
useDownloadManager: true,
notification: true,
mediaScannable: true,
title: 'pdfInfo.pdf',
path: `${saveDir}/` + `${Platform.OS==='ios'?this.state.certificateMetaData?.user_name:this.state.certificateMetaData?.user_name+".pdf"}`,
}
const configOptions = Platform.select({
ios: {
fileCache: configfb.fileCache,
title: configfb.title,
path: configfb.path,
appendExt: 'pdf',
},
android: configfb,
});
await RNFetchBlob.config(
configOptions
) .fetch('GET', `${this.state.catificationData.attributes?.document}`)
.then((res) => {
if (Platform.OS === 'ios')
{
RNFetchBlob.ios.openDocument(res.data);
const filePath = `${res.data}`;
let options = {
type: 'application/pdf',
url: `${filePath}.pdf`,
saveToFiles: true,
};
Share.share(options)
.then((resp) => console.log("then --> ",resp))
.catch((err) => console.log("catch --> ",err));
if(res.respInfo.status==200 && Platform.OS != 'ios'){
Alert.alert("File Downloaded Succesfully")
}
return true;
} else {
console.log('The file saved to android ', res.path()); return true;
} }) .catch((err) =>
{
return true;
});
}