背景:我們的應(yīng)用是RN實(shí)現(xiàn)的蔼夜,這次需要增加一個(gè)上傳下載并打開查看本地文檔的功能矩欠,于是就用到了這個(gè)查看文檔這個(gè)組件猾蒂,不過這次遇到一個(gè)蠻大的坑就是在安卓上使用出現(xiàn)如下的錯(cuò)誤,這個(gè)錯(cuò)誤耽擱了我1隐孽、2天時(shí)間癌椿,所以有必要記錄一下
我結(jié)合了上傳組件:react-native-file-selector? ? 以及下載組件:react-native-fs一起實(shí)現(xiàn)的這個(gè)功能,具體的使用可以查看我的其他博文
react-native-doc-viewer菱阵,可以在手機(jī)上直接打開文檔踢俄,支持遠(yuǎn)程和本地文檔。
支持的文檔格式:xls,ppt,doc,xlsx,pptx,docx,png,jpg,pdf,mp4送粱。支持iOS和Android褪贵。
這里我是做安卓的,所以主要描寫安卓相關(guān)的
插件安裝我就不多寫了抗俄,具體配置官網(wǎng)作者寫的很清楚:
安裝的時(shí)候需要注意的:
link完了手動(dòng)檢查一下安卓的各個(gè)目錄下的配置
下面附上我的一部分程序?qū)崿F(xiàn):
這里需要注意的是:
1脆丁,OpenFile.openDoc這個(gè)方法里,對(duì)于安卓的url需要加"file://"动雹,而ios不需要加
2槽卫,downloadDest就是你下載的文檔地址,這里我的地址用的是 :
? ? ? ?let dirs =Platform.OS ==='ios' ? RNFS.LibraryDirectoryPath : RNFS.ExternalStorageDirectoryPath;
? ? ? ?let downloadDest =`${dirs}/fileloca/`;
2胰蝠,里面的安卓的fileName和ios的fileNameOptional可以任意取歼培,這里我放的是我的文件名
3,安卓的fileType是沒有“.”的
/**
* 查看本地文檔
* fileType Default == "" you can use it, to set the File Extension
* (pdf,doc,xls,ppt etc) when in the Url the File Extension is missing.
*/
onPressLocalFile(downloadDest, fileName) {
? ? this.mkDir();
? ? console.log('onPressLocalFile: ', downloadDest, fileName)
? ? let fileType = fileName.substring(fileName.lastIndexOf('.') +1)
? ? let iosUrl = downloadDest +'/' + fileName
? ? let androidUrl ="file://" + downloadDest + fileName
? ?let filename = fileName.substring(0,fileName.lastIndexOf('.'))
? ?this.setState({animating:true});
? ? if (Platform.OS ==='ios') {
? ? ? ? ? ? OpenFile.openDoc([{
? ? ? ? ? ? url: iosUrl,
? ? ? ? ? ? fileNameOptional: filename
}], (error, url) => {
? ? ? ? ? ?if (error) {
? ? ? ? ? ? ? ? ?this.setState({animating:false});
? ? ? ? ? ? }else {
? ? ? ? ? ? ? ? ? ?this.setState({animating:false});
? ? ? ? ? ? ? ? ? ?console.log(url)
? ? ? ? ? ? }
? })
}else {
? ? OpenFile.openDoc([{
? ? ? ? ? ? url: androidUrl,
? ? ? ? ? ? fileName: filename,
? ? ? ? ? ? cache:false,
? ? ? ? ? ? fileType: fileType
}], (error, url) => {
? ? ?if (error) {
? ? ? ? ? ? ?this.setState({animating:false});
? ? ? }else {
? ? ? ? ? ? ?this.setState({animating:false});
? ? ? ? ? ? ? console.log(url)
? ? ? ?}
? ? })
? }
}
就這樣寫完后我跑了下程序茸塞,然后就報(bào)下面這種錯(cuò)躲庄,讓我頭疼了1、2天钾虐,心累
Failed to find configured root that contains
簡(jiǎn)直太難受了噪窘,試了很多種網(wǎng)上的方法都沒能訪問到這個(gè)根目錄
最后在主app的path目錄下再加了一個(gè)和他組件下的path名稱一樣的才解決了這個(gè)問題
1,組件自己目錄結(jié)構(gòu)
2效扫,主APP下添加的文件:
簡(jiǎn)直了倔监,改完直接想罵人了都,之前寫原生的時(shí)候文件名一樣的多寫一個(gè)都怕引用會(huì)錯(cuò)啥的菌仁,這RN的組件也是讓我服了浩习,必須記錄,以后引用RN組件的時(shí)候要多考慮下這些東西济丘,至于這個(gè)filePath呢是安卓原生的東西谱秽,就是系統(tǒng)存儲(chǔ)name和路徑,不知道的百度一下就懂了
想看下載文檔程序的看下一篇文檔:RN下載組件react-native-fs