在React Native的本机文件查看器中查看文件

在React Native的本机文件查看器中查看文件

这是一个 React Native 文件查看器示例,用于在本机文件查看器中查看文件。 我希望您已经看到 React Native 中的文件选择器示例,因为这是一个扩展示例。 此示例将介绍如何从文件系统中选取任何文件并在本机文件查看器中查看该文件。 如果您在文件选取时遇到任何问题,那么您可以查看 Filer Picker 示例,因为我们不会详细介绍该示例。 主要焦点将是文件查看器。

推荐:React Native应用程序中添加Firebase Analytics

为什么选择本机文件查看器?

这里本机文件查看器意味着我们不会在应用程序中查看文件,而是从文件选择器中选择文件并将文件 URL 传递给 FileViewer 组件提供者 react-native-file-viewer,该组件将触发原生iOS/Android文件查看器打开文件。

例如,

  1. 您选择了一个图像,然后它将在图像查看器中打开它,或者如果您有多个选项来查看图像,那么系统会要求您选择一个应用程序来查看图像
  2. 如果您选择了任何 pdf,那么它将从您的设备打开任何 pdf 阅读器
  3. 选择任何视频后,它将触发您设备的视频播放器播放视频

这是查看文件的最佳方式。 我知道很多人不会同意我的话“查看文件的最佳方式”但我个人觉得

  1. 它将减少创建和管理文件查看器以支持不同类型文件的辛苦工作
  2. 人们习惯于其设备的本机文件查看器,因此可以轻松地在本机文件查看器中查看文件
  3. 实现与本机文件查看器竞争的所有功能非常耗时
  4. 性能也是一个重点,许多本机文件查看器已经处理设备中可用图像的缓存和所有内容。

我想我已经清楚了为什么我更喜欢本机文件查看器。

如何在本机文件查看器中查看任何文件?

要从我们的应用程序触发任何本机文件查看器,我们将使用 FileViewer 组件提供者 react-native-file-viewer。 这是 2 个步骤的过程

  1. 首先,我们使用任何文件选择器选择一个文件,或者您也可以获取任何下载文件的路径。 我在这里使用 反应本机文档选择器 用于文件拾取
    const res = await DocumentPicker.pick({
        type: (DocumentPicker.types.allFiles),
    });
    singleFile = res;
  2. 现在在 FileViewer 中传递文件 URI 以打开文件
    let uri = singleFile.uri;
    if (Platform.OS === 'ios') {
      uri = res.uri.replace('file://', '');
    }
    FileViewer.open(uri)
    .then(() => {
      //Can do anything you want after opening the file successfully
      console.log('Success');
    })
    .catch(_err => {
      //Handle failure here
      console.log(_err);
    });

    请注意,如果是 iOS,我们需要从文件路径中删除“file://”前缀。

React Native 文件查看器示例概述

在此示例中,我们将创建一个带有一个按钮的屏幕。 单击按钮后,我们将触发文件选择器,选择文件后,我们将在本机文件查看器中打开该文件。

如果您在文件选择器方面遇到任何挑战,那么您可以查看 React Native 中的文件选择器示例,它将帮助您解决问题。 现在让我们开始示例。

制作 React Native 应用程序

React Native 入门将帮助您更多地了解如何制作 React Native 项目。 我们将使用 React Native 命令行界面来制作我们的 React Native 应用程序。

如果您之前安装了全局的react-native-cli软件包,请将其删除,因为它可能会导致意外问题:

npm uninstall -g react-native-cli @react-native-community/cli

运行以下命令创建一个新的 React Native 项目

npx react-native init ProjectName

如果你想使用特定的 React Native 版本启动一个新项目,你可以使用 –version 参数:

npx react-native init ProjectName --version X.XX.X

注意如果上述命令失败,您可能使用的是旧版本 react-native 或者 react-native-cli 在您的电脑上全局安装。 尝试卸载 cli 并使用 npx 运行 cli。

这将在项目目录中创建一个带有名为 App.js 的索引文件的项目结构。

安装依赖

现在我们需要安装该项目所需的依赖项。 打开终端并跳转到您的项目

cd ProjectName

对于文件选择器安装 react-native-document-picker 使用以下命令

npm install react-native-document-picker --save

现在我们需要安装 react-native-file-viewer 我们将从中导入 FileViewer 成分。 请运行以下命令来安装它

npm install react-native-file-viewer --save

依赖关系的链接

现在我们需要链接 react-native-document-picker, 和 react-native-file-viewer 使用

react-native link react-native-document-picker
react-native link react-native-file-viewer

CocoaPods 安装

现在我们需要安装 pod

cd ios && pod install && cd ..

React Native 文件查看器的代码

在任何代码编辑器中打开 App.js 并将代码替换为以下代码

应用程序.js

// React Native File Viewer Example to View Files in Native File Viewer
// https://aboutreact.com/react-native-file-viewer/

// Import React
import React from 'react';
// Import core components
import {
  StyleSheet,
  View,
  Text,
  TouchableOpacity,
  Platform,
} from 'react-native';

// Import File Viewer to View Files in Native File Viewer
import FileViewer from 'react-native-file-viewer';
// Import DocumentPicker to pick file to view
import DocumentPicker from 'react-native-document-picker';

const App = () => {
  const selectOneFile = async () => {
    // To Select File
    try {
      const res = await DocumentPicker.pick({
        // Provide which type of file you want user to pick
        type: (DocumentPicker.types.allFiles),
        // There can me more options as well
        // DocumentPicker.types.allFiles
        // DocumentPicker.types.images
        // DocumentPicker.types.plainText
        // DocumentPicker.types.audio
        // DocumentPicker.types.pdf
      });
      if (res) {
        let uri = res.uri;
        if (Platform.OS === 'ios') {
          // Remove 'file://' from file path for FileViewer
          uri = res.uri.replace('file://', '');
        }
        console.log('URI : ' + uri);
        FileViewer.open(uri)
          .then(() => {
            // Do whatever you want
            console.log('Success');
          })
          .catch(_err => {
            // Do whatever you want
            console.log(_err);
          });
      }
    } catch (err) {
      // Handling Exception
      if (DocumentPicker.isCancel(err)) {
        // If user canceled the document selection
        alert('Canceled');
      } else {
        // For Unknown Error
        alert('Unknown Error: ' + JSON.stringify(err));
        throw err;
      }
    }
  };
  return (
    <View style={styles.mainBody}>
      <View style={{ alignItems: 'center' }}>
        <Text
          style={{
            fontSize: 30,
            textAlign: 'center'
          }}>
          Native file viewer for React Native
        </Text>
        <Text
          style={{
            fontSize: 25,
            marginTop: 20,
            textAlign: 'center'
          }}>
          Preview any type of file supported by the mobile device
        </Text>
        <Text
          style={{
            fontSize: 25,
            marginTop: 20,
            marginBottom: 30,
            textAlign: 'center',
          }}>
          www.aboutreact.com
        </Text>
      </View>
      <TouchableOpacity
        style={styles.buttonStyle}
        activeOpacity={0.5}
        onPress={selectOneFile}>
        <Text style={styles.buttonTextStyle}>
          Select File to View
        </Text>
      </TouchableOpacity>
    </View>
  );
};

const styles = StyleSheet.create({
  mainBody: {
    flex: 1,
    justifyContent: 'center',
    padding: 20,
  },
  buttonStyle: {
    backgroundColor: '#307ecc',
    borderWidth: 0,
    color: '#FFFFFF',
    borderColor: '#307ecc',
    height: 40,
    alignItems: 'center',
    borderRadius: 30,
    marginLeft: 35,
    marginRight: 35,
    marginTop: 15,
  },
  buttonTextStyle: {
    color: '#FFFFFF',
    paddingVertical: 10,
    fontSize: 16,
  },
});

export default App;

运行 React Native 应用程序

再次打开终端并使用跳转到您的项目。

cd ProjectName

1. 启动 Metro Bundler

首先,您需要启动 Metro,React Native 附带的 JavaScript 捆绑器。 要启动 Metro 捆绑程序,请运行以下命令

npx react-native start

一旦您启动 Metro Bundler,它将永远在您的终端上运行,直到您将其关闭。 让 Metro Bundler 在自己的终端中运行。 打开一个新终端并运行该应用程序。

2.启动React Native应用程序

在 Android 虚拟设备或真实调试设备上运行项目

npx react-native run-android

或在 iOS 模拟器上运行(仅限 macOS)

npx react-native run-ios

输出截图

安卓

文件查看器示例 Android 屏幕截图 1 文件查看器示例 Android 屏幕截图 2 文件查看器示例 Android 屏幕截图 3 文件查看器示例 Android 屏幕截图 4

iOS系统

文件查看器示例 iOS 屏幕截图 1 RNFileViewerExampleiOS2 RNFileViewerExampleiOS3

这是使用本机文件查看器在 React Native 中查看文件的方式。 如果您有任何疑问或想分享有关该主题的内容,您可以在下面发表评论或在此处联系我们。

推荐:WooCommerce主题Oxygen WooCommerce主题


发表评论