React-Native-打开文件

本地应用打开文件 react-native-file-opener

  • NPM install

    1
    npm install --save react-native-file-opener
  • IOS install

    1
    2
    在Xcode中,将node_modules/react-native-file-opener/ios/RNFileOpener.xcodeproj添加到项目的Libraries目录;
    将Libraries/RNFileOpener.xcodeproj/Products/libRNFileOpener.a拖拽到Build Phases -> Link Binary With Libraries中。
  • Android install

    1
    2
    3
    4
    // file: android/settings.gradle
    ...
    include ':react-native-file-opener'
    project(':react-native-file-opener').projectDir = new File(settingsDir, '../node_modules/react-native-file-opener/android')
    1
    2
    3
    4
    5
    6
    // file: android/app/build.gradle
    ...
    dependencies {
    ...
    compile project(':react-native-file-opener')
    }
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    // file: MainActivity.java
    ...
    import com.fileopener.FileOpenerPackage;//<- import package
    public class MainActivity extends ReactActivity {
    @Override
    protected List<ReactPackage> getPackages() {
    return Arrays.<ReactPackage>asList(
    new MainReactPackage(),
    new FileOpenerPackage() //<- Add package
    );
    }
    ...
    }
  • Usage
    在上一篇React-Native-上传下载例子的基础上,添加如下代码

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    ...
    import FileOpener from 'react-native-file-opener';
    ...
    class TestFileStream extends Component {
    ...
    openFile(fileName) {
    const FilePath = Platform.OS === 'android' ? dirs.DCIMDir + '/' + fileName : dirs.DocumentDir + '/' + fileName;
    const FileMimeType = 'image/jpg';
    FileOpener.open(
    FilePath,
    FileMimeType
    ).then((msg) => {
    console.log('success!!')
    },(err) => {
    console.log('打开失败:', err)
    });
    }
    ...
    }
    export default TestFileStream;