背景:我的app应用使用react-native开发的。有个需求是上传、下载并打开查看本地文档的功能,于是就用到了这个查看文档这个组件。安卓上使用出现如下的错误,记录一下。
结合组件
页面是使用react-native-webview嵌入页面式。上传组件:h5里的antd的上传组件,下载组件:react-native-fs,直接打开文件:react-native-doc-viewer,可以在手机上打开文档,支持远程和本地文档。
支持打开的文件格式: xls,ppt,doc,xlsx,pptx,docx,png,jpg,pdf,mp4。支持iOS和Android
下载依赖
yarn add -D react-native-doc-viewer
依赖长时间没有维护源码需要修改。
- 进入node_modules找到react-native-doc-viewer文件夹
- 找到文件RNReactNativeDocViewerModule.java,我这边路径是:node_modules\react-native-doc-viewer\android\src\main\java\com\reactlibrary\RNReactNativeDocViewerModule.java
3.删除
import com.facebook.react.views.webview.ReactWebViewManager;,删除之后就正常运行了。
实现部分
- OpenFile.openDoc这个方法里,对于安卓的url需要加"file://" ,而ios不需要加
const filePath = Platform.select({
ios: RNFS.DocumentDirectoryPath,
android: 'file://'+ RNFS.ExternalDirectoryPath
}) +'/user_files/'+ fileName;
// android
OpenFile.openDoc([{
// 文件地址
url: filePath,
// 文件名称
fileName: opt.fileName,
// 缓存
cache: false,
// 文件后缀没有.
fileType: opt.fileType
}], (error: any, url: any) => {
if (error) {
if (typeof error === 'string' && /Activity not found to handle/.test(error)) {
Alert.alert('无可用打开方式');
} else if ( typeof error === 'string' && /Permission Denial/.test(error) ) {
Alert.alert('没有打开文件权限,请确认已授权应用读取本地存储');
}
}
});
// ios
OpenFile.openDoc([{
// 文件地址
url: opt.filePath,
// 文件名称
fileNameOptional: opt.fileName
}], (error: any, url: any) => {
if (error) {
if (typeof error === 'string' && /Activity not found to handle/.test(error)) {
Alert.alert('无可用打开方式');
} else if ( typeof error === 'string' && /Permission Denial/.test(error) ) {
Alert.alert('没有打开文件权限,请确认已授权应用读取本地存储');
}
}
})