使用React Native应用程序在Google Drive上存储检索文件

使用React Native应用程序在Google Drive上存储检索文件

在这篇文章中,我们将了解如何使用 React Native 应用程序在 Google Drive 上存储/检索文件。 在此示例中,我们将了解如何集成 Google Drive 在 React Native App 中执行以下操作,该操作适用于 Android 和 iOS。

  1. 在 Google 云端硬盘上创建目录
  2. 选择并上传 Google 云端硬盘上的任何文件
  3. 列出 Google 云端硬盘中的文件(所有文件 + 筛选的文件)
  4. 从 Google 云端硬盘删除任何文件
  5. 从 Google 云端硬盘下载任何文件

我们都知道Google Drive是Google开发的文件存储和同步服务。 Google Drive 允许用户在其服务器上存储文件、跨设备同步文件以及共享文件。

如果我们谈论为什么人们将 Google Drive 与任何移动应用程序集成? 答案是存储移动应用程序的备份文件并存储属于用户的数据,并且应用程序不需要它来进行分析或任何其他用途。

推荐:手工艺术家和工匠WooCommerce主题Zass主题

如何将 Google Drive 与 React Native 应用程序集成

让我们看看如何集成 Google Drive。

谷歌提供了一个非常好的 API套件 用于将 Google Drive 与任何平台集成。 我们可以简单地使用这些 HTTP API 通过 fetch 来管理 Google Drive 文件,但在准备这个示例时我们发现 反应本机谷歌驱动器 API 包装器,使用库非常简单,它提供了所有必要的功能作为函数(内部它使用相同的 Google 云端硬盘 V3 API)。 我们将在本示例中使用相同的内容。

要访问任何 Google Drive API,我们需要具有适当权限的令牌才能访问文件。 我们可以通过在应用程序中提供 Google Sign in 功能(具有访问 Google Drive 的权限)来获取此令牌。 该库不提供任何授权机制,因此我们将使用外部 Google Sign In 库进行登录,一旦用户登录,我们可以请求 Google 向我们提供访问驱动器的令牌。

您可以使用 Google Drive API 做什么?

  • 从 Google 云端硬盘下载文件并将文件上传到 Google 云端硬盘
  • 搜索存储在 Google 云端硬盘中的文件和文件夹。 创建复杂的搜索查询,返回文件资源中的任何文件元数据字段
  • 让用户共享文件、文件夹和驱动器以协作处理内容
  • 结合Google Picker API搜索Google Drive中的所有文件,然后返回文件名、URL、最后修改日期和用户
  • 创建专用的云端硬盘文件夹来存储应用程序的数据,以便应用程序无法访问存储在 Google 云端硬盘中的所有用户内容。 请参阅存储特定于应用程序的数据

Google Drive 示例解释

在此示例中,我们将在第一个屏幕上创建 Google 登录,用户登录后,他/她将看到主屏幕,其中包含导航到不同屏幕以上传、列出、删除和下载文件的所有选项。 我们为每个操作创建了单独的屏幕,以便您可以了解执行该操作到底需要什么。

现在让我们从示例开始。

制作 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

1. 对于此示例,我们需要在我们的应用程序中使用 Google 登录,您可以查看 React Native Android 和 iOS 应用程序中的 Google 登录示例,完成 Google 登录后,您可以返回并继续下一步。

如果您完成了 Google Sign In 集成,您是否注意到 范围

我们需要将授权令牌发送到 Drive API 调用。 在生成此令牌时,我们定义 范围 访问用户数据。 当我们在应用程序中配置登录时,我们定义了这些 范围 Google 将在用户登录后向其确认。 您可以根据需要添加范围, 这里 您可以根据不同的要求找到要添加的范围列表。 我们为此示例添加了如此多的范围,因为我们将使用 Google Drive API 的最大功能。

2. 完成 Google 登录后,您可以安装以下依赖项以在 Google Drive 上执行不同的操作

npm install react-native-google-drive-api-wrapper --save

3.上述依赖项需要以下依赖项来下载文件,因此我们还需要安装它

npm install react-native-fs --save

4. 接下来,我们将使用文档选择器来选择要上传到 Google Drive 的文件,要使用文档选择器安装以下依赖项

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

5. 这足以从 Google Drive 存储和检索文件,但在本例中,我们还将使用 React 导航,因为我们将切换屏幕。 因此还安装以下react-navigation依赖项

npm install @react-navigation/native --save

其他用于反应导航的支持库

npm install react-native-reanimated react-native-gesture-handler react-native-screens react-native-safe-area-context @react-native-community/masked-view --save
npm install @react-navigation/stack --save

CocoaPods 安装

现在我们需要安装 pod

cd ios && pod install && cd ..

从 Google API 控制台启用 Google Drive API

要在我们的应用程序中使用 Google Drive API,我们需要启用它。 要启用 Google Drive API,请按照以下步骤操作:

  1. 打开 谷歌 API 控制台
  2. 在顶部标题中找到项目(您为 Google 登录创建的 Firebase 项目)
  3. 在仪表板上,您将看到“启用 APIS 和服务”,单击它
  4. 在搜索栏中搜索“google Drive”,您将看到一些结果,只需单击 谷歌云端硬盘API
  5. 请启用它,一旦您这样做,我们已成功提供权限

React_native_google_drive_ios_permission

安卓权限

在此示例中,我们将把下载的文件存储在外部存储中,为此我们必须向 AndroidManifest.xml 文件。 请在 AndroidMnifest.xml 中添加以下权限。 去 YourProject -> android -> app -> main -> AndroidMnifest.xml

<uses-permission
  android:name="android.permission.WRITE_EXTERNAL_STORAGE"
/>
允许目的
写外部存储在外部存储中创建任何文件

文件下载 Android 权限
有关权限的更多信息,您可以查看这篇文章。

IOS权限

为了让 RNFS 获取下载文件的路径,我们需要在 iOS 中添加以下权限

1.打开项目 YourProject -> ios -> YourProject.xcworkspace 在 XCode 中。 单击左侧边栏中的“项目”

2.选择info选项卡,即info.plist

3. 单击加号按钮添加以下权限键和值,弹出权限对话框时将显示这些键和值。

钥匙价值
隐私 – 文件提供者存在使用说明应用程序需要文件提供程序

React_native_google_drive_ios_permission.png

项目目录/文件结构

如果一切顺利,那么您就可以进入下一步了。

要开始此示例,您需要创建以下目录/文件结构。 这将有一个包含我们所有代码的 src 目录,src 目录将还有两个目录 auth 和 googleDrivescreens。 所有这些目录将包含以下文件作为完整示例。

react_native_google_drive_example_struct

你可以看到

  1. 应用程序.js 包含主导航
  2. src/HomeScreen.js 用于主屏幕列表
  3. src/auth/GoogleLoginScreen.js 用于 Google 登录
  4. src/googleDrivescreens/GDUploadFileScreen.js 将文件上传到 Google 云端硬盘
  5. src/googleDrivescreens/GDFilesListingScreen.js 用于列出 Google 云端硬盘文件
  6. src/googleDrivescreens/GDSingleFileScreen.js 获取文本文件的内容,而无需将其下载到移动设备中
  7. src/googleDrivescreens/GDDeleteFileScreen.js 删除任何 Google 云端硬盘文件
  8. src/googleDrivescreens/GDDownloadFileScreen.js 将任何 Google Drive 文件下载到移动设备中

在 Google Drive 上存储/检索文件的代码

您可以在下面找到完整的代码。 我们请求您访问 官方图书馆页面 了解我们用于创建此示例的所有函数。

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

应用程序.js

// Store/Retrieve Files on Google Drive using React Native App
// https://aboutreact.com/react-native-google-drive/
import 'react-native-gesture-handler';

// Import React
import React from 'react';

// Import Navigators from React Navigation
import {NavigationContainer} from '@react-navigation/native';
import {createStackNavigator} from '@react-navigation/stack';

// Import all the screens needed
import GoogleLoginScreen from './src/auth/GoogleLoginScreen';
import HomeScreen from './src/HomeScreen';
import GDUploadFileScreen from './src/googleDrivescreens/GDUploadFileScreen';
import GDFilesListingScreen from './src/googleDrivescreens/GDFilesListingScreen';
import GDSingleFileScreen from './src/googleDrivescreens/GDSingleFileScreen';
import GDDeleteFileScreen from './src/googleDrivescreens/GDDeleteFileScreen';
import GDDownloadFileScreen from './src/googleDrivescreens/GDDownloadFileScreen';

const Stack = createStackNavigator();

const App = () => {
  return (
    <NavigationContainer>
      <Stack.Navigator
        initialRouteName="GoogleLoginScreen"
        screenOptions={{
          headerStyle: {
            backgroundColor: '#f4511e', //Set Header color
          },
          headerTintColor: '#fff', //Set Header text color
          headerTitleStyle: {
            fontWeight: 'bold', //Set Header text style
          },
        }}>
        <Stack.Screen
          name="GoogleLoginScreen"
          component={GoogleLoginScreen}
          // Hiding header
          options={{headerShown: false}}
        />
        <Stack.Screen
          name="HomeScreen"
          component={HomeScreen}
          options={{title: 'Google Drive Example'}}
        />
        <Stack.Screen
          name="GDUploadFileScreen"
          component={GDUploadFileScreen}
          options={{title: 'Upload File'}}
        />
        <Stack.Screen
          name="GDFilesListingScreen"
          component={GDFilesListingScreen}
          options={{title: 'Files'}}
        />
        <Stack.Screen
          name="GDSingleFileScreen"
          component={GDSingleFileScreen}
          options={{title: 'File Content'}}
        />
        <Stack.Screen
          name="GDDeleteFileScreen"
          component={GDDeleteFileScreen}
          options={{title: 'Delete File'}}
        />
        <Stack.Screen
          name="GDDownloadFileScreen"
          component={GDDownloadFileScreen}
          options={{title: 'Download File'}}
        />
      </Stack.Navigator>
    </NavigationContainer>
  );
};

export default App;

src/HomeScreen.js

// Store/Retrieve Files on Google Drive using React Native App
// https://aboutreact.com/react-native-google-drive/

// Import React in our code
import React, {useState, useEffect} from 'react';

// Import all the components we are going to use
import {
  SafeAreaView,
  StyleSheet,
  Text,
  View,
  Image,
  TouchableOpacity,
  ScrollView,
} from 'react-native';

// For Google Signin
import {GoogleSignin} from 'react-native-google-signin';

const HomeScreen = ({navigation, route}) => {
  //route.params.userInfo
  // State Defination
  const (userInfo, setUserInfo) = useState(null);

  React.useLayoutEffect(() => {
    navigation.setOptions({
      headerRight: () => (
        <TouchableOpacity onPress={_signOut}>
          <Text style={{marginRight: 10, color: 'white'}}>
            Logout
          </Text>
        </TouchableOpacity>
      ),
    });
  }, (navigation));

  useEffect(() => {
    setUserInfo(route.params.userInfo);
  }, ());

  // To sign out from Google Login
  const _signOut = async () => {
    // Remove user session from the device.
    try {
      await GoogleSignin.revokeAccess();
      await GoogleSignin.signOut();
      // Removing user Info
      setUserInfo(null);
      navigation.replace('GoogleLoginScreen');
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <SafeAreaView style={styles.container}>
      <View style={styles.container}>
        <>
          <View style={{flexDirection: 'row'}}>
            {userInfo ? (
              <Image
                source={{uri: userInfo.user.photo}}
                style={styles.imageStyle}
              />
            ) : null}
            <View style={{flexDirection: 'column'}}>
              <Text style={styles.text}>
                User Name: {userInfo ? userInfo.user.name : ''}
              </Text>
              <Text style={styles.text}>
                Use Email: {userInfo ? userInfo.user.email : ''}
              </Text>
            </View>
          </View>
          <ScrollView>
            <TouchableOpacity
              style={styles.buttonStyle}
              onPress={() =>
                navigation.navigate('GDUploadFileScreen')
              }>
              <Text>Select and Upload File on Google Drive</Text>
            </TouchableOpacity>
            <TouchableOpacity
              style={styles.buttonStyle}
              onPress={() =>
                navigation.navigate(
                  'GDFilesListingScreen',
                  {type: 'all'}
                )
              }>
              <Text>Listing of Files from Google Drive</Text>
            </TouchableOpacity>
            <TouchableOpacity
              style={styles.buttonStyle}
              onPress={() =>
                navigation.navigate(
                  'GDFilesListingScreen',
                  {type: 'filtered'}
                )
              }>
              <Text style={{textAlign: 'center'}}>
                Get Specific File Content from Google Drive
              </Text>
            </TouchableOpacity>
            <TouchableOpacity
              style={styles.buttonStyle}
              onPress={() =>
                navigation.navigate('GDSingleFileScreen')
              }>
              <Text style={{textAlign: 'center'}}>
                Get Single File Content from Google Drive
              </Text>
            </TouchableOpacity>
            <TouchableOpacity
              style={styles.buttonStyle}
              onPress={() =>
                navigation.navigate('GDDeleteFileScreen')
              }>
              <Text>Delete any File from Google Drive</Text>
            </TouchableOpacity>
            <TouchableOpacity
              style={styles.buttonStyle}
              onPress={() =>
                navigation.navigate('GDDownloadFileScreen')
              }>
              <Text>Download File from Google Drive</Text>
            </TouchableOpacity>
          </ScrollView>
        </>
        <Text style={styles.footerHeading}>
          Store/Retrieve Files on Google Drive
        </Text>
        <Text style={styles.footerText}>www.aboutreact.com</Text>
      </View>
    </SafeAreaView>
  );
};

export default HomeScreen;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
    padding: 10,
  },
  imageStyle: {
    width: 40,
    height: 40,
    borderRadius: 40 / 2,
    marginRight: 16,
  },
  buttonStyle: {
    alignItems: 'center',
    backgroundColor: '#DDDDDD',
    padding: 10,
    width: 300,
    marginTop: 30,
  },
  footerHeading: {
    fontSize: 18,
    textAlign: 'center',
    color: 'grey',
  },
  footerText: {
    fontSize: 16,
    textAlign: 'center',
    color: 'grey',
  },
});

src/auth/GoogleLoginScreen.js

请更换 REPLACE_YOUR_WEBCLIENT_ID 和你的 网络客户端ID

// Store/Retrieve Files on Google Drive using React Native App
// https://aboutreact.com/react-native-google-drive/

// Import React in our code
import React, {useState, useEffect} from 'react';

// Import all the components we are going to use
import {
  SafeAreaView,
  StyleSheet,
  Text,
  View,
  ActivityIndicator,
} from 'react-native';

// For Google Signin
import {
  GoogleSignin,
  GoogleSigninButton,
  statusCodes,
} from 'react-native-google-signin';

const GoogleLoginScreen = ({navigation}) => {
  const (loading, setLoading) = useState(true);

  useEffect(() => {
    // Initial configuration
    GoogleSignin.configure({
      // Mandatory method to call before calling signIn()
      scopes: (
        'https://www.googleapis.com/auth/drive',
        'https://www.googleapis.com/auth/drive.file',
        'https://www.googleapis.com/auth/drive.appdata',
        'https://www.googleapis.com/auth/drive.metadata',
        'https://www.googleapis.com/auth/drive.readonly',
        'https://www.googleapis.com/auth/drive.metadata.readonly',
        'https://www.googleapis.com/auth/drive.apps.readonly',
        'https://www.googleapis.com/auth/drive.photos.readonly',
      ),
      // Repleace with your webClientId
      // Generated from Firebase console
      webClientId: 'REPLACE_YOUR_WEBCLIENT_ID',
    });
    // Check if user is already signed in
    _isSignedIn();
  }, ());

  // To prompt google Signin Widget
  const _signIn = async () => {
    try {
      await GoogleSignin.hasPlayServices({
        // Check if device has Google Play Services installed
        // Always resolves to true on iOS
        showPlayServicesUpdateDialog: true,
      });
      const userInfo = await GoogleSignin.signIn();
      console.log('User Info --> ', userInfo);
      navigation.replace('HomeScreen', {userInfo: userInfo});
    } catch (error) {
      if (error.code === statusCodes.SIGN_IN_CANCELLED) {
        alert('User Cancelled the Login Flow');
      } else if (error.code === statusCodes.IN_PROGRESS) {
        alert('Signing In');
      } else if (
        error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE
      ) {
        alert('Play Services Not Available or Outdated');
      } else {
        console.log('error.message', JSON.stringify(error));
        alert(error.message);
      }
    }
  };

  // Check if User is signned in or not?
  const _isSignedIn = async () => {
    const isSignedIn = await GoogleSignin.isSignedIn();
    if (isSignedIn) {
      console.log('User is already signed in');
      // Get User Info if user is already signed in
      try {
        let info = await GoogleSignin.signInSilently();
        console.log('User Info --> ', info);
        navigation.replace('HomeScreen', {userInfo: info});
      } catch (error) {
        if (error.code === statusCodes.SIGN_IN_REQUIRED) {
          alert('User has not signed in yet');
          console.log('User has not signed in yet');
        } else {
          alert("Unable to get user's info");
          console.log("Unable to get user's info", error);
        }
      }
    }
    setLoading(false);
  };

  if (loading) {
    return (
      <View style={styles.container}>
        <ActivityIndicator size="large" color="#0000ff" />
      </View>
    );
  } else {
    return (
      <SafeAreaView style={styles.container}>
        <View style={styles.container}>
          <Text style={styles.titleText}>
            Store / Retrieve Files from Google Drive{' '}
            using React Native App
          </Text>
          <View style={styles.container}>
            <GoogleSigninButton
              style={{width: 312, height: 48}}
              size={GoogleSigninButton.Size.Wide}
              color={GoogleSigninButton.Color.Dark}
              onPress={_signIn}
            />
          </View>
          <Text style={styles.footerHeading}>
            Store/Retrieve Files on Google Drive
          </Text>
          <Text style={styles.footerText}>www.aboutreact.com</Text>
        </View>
      </SafeAreaView>
    );
  }
};

export default GoogleLoginScreen;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
    padding: 10,
  },
  titleText: {
    fontSize: 20,
    fontWeight: 'bold',
    textAlign: 'center',
    padding: 20,
  },
  footerHeading: {
    fontSize: 18,
    textAlign: 'center',
    color: 'grey',
  },
  footerText: {
    fontSize: 16,
    textAlign: 'center',
    color: 'grey',
  },
});

src/googleDrivescreens/GDUploadFileScreen.js

// Store/Retrieve Files on Google Drive using React Native App
// https://aboutreact.com/react-native-google-drive/

// Import React in our code
import React, {useState} from 'react';

// Import all the components we are going to use
import {
  SafeAreaView,
  StyleSheet,
  Text,
  View,
  ActivityIndicator,
  TouchableOpacity,
  TextInput,
} from 'react-native';

// For Google Signin
import {GoogleSignin} from 'react-native-google-signin';
// For Google Drive
import GDrive from 'react-native-google-drive-api-wrapper';
// To manage local files
import RNFS from 'react-native-fs';
// To pick the file from local file system
import DocumentPicker from 'react-native-document-picker';

const APP_DIRECTORY = 'AboutReactAppExample';

const GDUploadFileScreen = () => {
  // State Defination
  const (loading, setLoading) = useState(false);
  const (filePath, setFilePath) = useState({});
  const (inputTextValue, setInputTextValue) = useState('');

  const _chooseFile = async () => {
    // Opening Document Picker to select one file
    try {
      const fileDetails = await DocumentPicker.pick({
        // Provide which type of file you want user to pick
        type: (DocumentPicker.types.allFiles),
      });
      console.log('fileDetails : ' + JSON.stringify(fileDetails));
      // Setting the state for selected File
      setFilePath(fileDetails);
    } catch (error) {
      setFilePath({});
      // If user canceled the document selection
      alert(
        DocumentPicker.isCancel(error)
          ? 'Canceled'
          : 'Unknown Error: ' + JSON.stringify(error),
      );
    }
  };

  const _initGoogleDrive = async () => {
    // Getting Access Token from Google
    let token = await GoogleSignin.getTokens();
    if (!token) return alert('Failed to get token');
    console.log('res.accessToken =>', token.accessToken);
    // Setting Access Token
    GDrive.setAccessToken(token.accessToken);
    // Initializing Google Drive and confirming permissions
    GDrive.init();
    // Check if Initialized
    return GDrive.isInitialized();
  };

  const _uploadDriveDataImage = async () => {
    try {
      // Check if file selected
      if (Object.keys(filePath).length == 0)
        return alert('Please Select any File');
      setLoading(true);
      if (!(await _initGoogleDrive())) {
        return alert('Failed to Initialize Google Drive');
      }
      // Convert Selected File into base64
      let fileContent = await RNFS.readFile(filePath.uri, 'base64');
      // console.log('fileContent -> ', JSON.stringify(fileContent));
      // Create Directory on Google Device
      let directoryId = await GDrive.files.safeCreateFolder({
        name: APP_DIRECTORY,
        parents: ('root'),
      });
      console.log('directoryId -> ', directoryId);
      // Create Multipart and Upload
      let result = await GDrive.files.createFileMultipart(
        fileContent,
        filePath.type,
        {
          parents: (directoryId),
          name: filePath.name,
        },
        true,
      );
      // Check upload file response for success
      if (!result.ok) return alert('Uploading Failed');
      // Getting the uploaded File Id
      let fileId = await GDrive.files.getId(
        filePath.name,
        (directoryId),
        filePath.type,
        false,
      );
      alert(`Uploaded Successfull. File Id: ${fileId}`);
      setFilePath({});
    } catch (error) {
      console.log('Error->', error);
      alert(`Error-> ${error}`);
    }
    setLoading(false);
  };

  const _uploadDriveData = async () => {
    try {
      // Check if file selected
      if (!inputTextValue) return alert('Please Enter Some Input');
      setLoading(true);
      if (!(await _initGoogleDrive())) {
        return alert('Failed to Initialize Google Drive');
      }
      // Create Directory on Google Device
      let directoryId = await GDrive.files.safeCreateFolder({
        name: APP_DIRECTORY,
        parents: ('root'),
      });
      console.log('directoryId -> ', directoryId);
      let fileName = new Date().getTime() + '.txt';
      // Check upload file response for success
      let result = await GDrive.files.createFileMultipart(
        inputTextValue,
        'application/text',
        {
          parents: (directoryId),
          name: fileName,
        },
        false,
      );
      // Check upload file response for success
      if (!result.ok) return alert('Uploading Failed');
      // Getting the uploaded File Id
      let fileId = await GDrive.files.getId(
        fileName,
        (directoryId),
        'application/text',
        false,
      );
      setInputTextValue('');
      alert(`Uploaded Successfull. File Id: ${fileId}`);
    } catch (error) {
      console.log('Error->', error);
      alert(`Error-> ${error}`);
    }
    setLoading(false);
  };

  return (
    <>
      {loading ? (
        <View style={styles.container}>
          <ActivityIndicator size="large" color="#0000ff" />
        </View>
      ) : (
        <SafeAreaView style={{flex: 1}}>
          <View style={styles.container}>
            <Text style={styles.titleText}>
              Upload Input Text as File on Google Drive
            </Text>
            <View style={styles.container}>
              <TextInput
                style={styles.inputStyle}
                placeholder="Please Enter Text to Upload as a File"
                onChangeText={(input) => setInputTextValue(input)}
                value={inputTextValue}
              />
              <TouchableOpacity
                style={styles.buttonStyle}
                onPress={_uploadDriveData}>
                <Text>uploadDriveFile</Text>
              </TouchableOpacity>
              <View style={styles.deviderContainer}>
                <View style={styles.devider} />
                <Text>OR</Text>
                <View style={styles.devider} />
              </View>
              <Text style={styles.titleText}>
                Choose File and Upload to Google Drive
              </Text>
              <TouchableOpacity
                activeOpacity={0.5}
                style={styles.buttonStyle}
                onPress={_chooseFile}>
                <Text style={styles.textStyleWhite}>
                  Choose Image{' '}
                  (Current Selected: {filePath.uri ? 1 : 0})
                </Text>
              </TouchableOpacity>
              <TouchableOpacity
                style={styles.buttonStyle}
                onPress={_uploadDriveDataImage}>
                <Text>uploadDriveDataImage</Text>
              </TouchableOpacity>
            </View>
            <Text style={styles.footerHeading}>
              Store/Retrieve Files on Google Drive
            </Text>
            <Text style={styles.footerText}>www.aboutreact.com</Text>
          </View>
        </SafeAreaView>
      )}
    </>
  );
};

export default GDUploadFileScreen;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    padding: 10,
  },
  titleText: {
    fontSize: 16,
    fontWeight: 'bold',
    textAlign: 'center',
    padding: 20,
  },
  imageStyle: {
    width: 20,
    height: 30,
    resizeMode: 'contain',
  },
  buttonStyle: {
    alignItems: 'center',
    backgroundColor: '#DDDDDD',
    padding: 10,
    width: 300,
    marginTop: 16,
  },
  footerHeading: {
    fontSize: 18,
    textAlign: 'center',
    color: 'grey',
  },
  footerText: {
    fontSize: 16,
    textAlign: 'center',
    color: 'grey',
  },
  deviderContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginVertical: 16,
  },
  devider: {
    width: 150,
    height: 1,
    marginHorizontal: 16,
    backgroundColor: 'grey',
  },
  inputStyle: {
    height: 40,
    width: 300,
    borderColor: 'grey',
    borderWidth: 1,
    padding: 10,
  },
});

src/googleDrivescreens/GDFilesListingScreen.js

// Store/Retrieve Files on Google Drive using React Native App
// https://aboutreact.com/react-native-google-drive/

// Import React in our code
import React, {useState, useEffect} from 'react';

// Import all the components we are going to use
import {
  SafeAreaView,
  StyleSheet,
  Text,
  View,
  ActivityIndicator,
  FlatList,
} from 'react-native';

// For Google Signin
import {GoogleSignin} from 'react-native-google-signin';
// For Google Drive
import GDrive from 'react-native-google-drive-api-wrapper';

const APP_DIRECTORY = 'AboutReactAppExample';

const GDFilesListingScreen = ({route}) => {
  // State Defination
  const (listData, setListData) = useState(());
  const (loading, setLoading) = useState(true);

  useEffect(() => {
    if (route.params.type == 'all') _getAllFilesList();
    else _getAllMyAppFilesList();
  }, ());

  const _initGoogleDrive = async () => {
    // Getting Access Token from Google
    let token = await GoogleSignin.getTokens();
    if (!token) return alert('Failed to get token');
    console.log('res.accessToken =>', token.accessToken);
    // Setting Access Token
    GDrive.setAccessToken(token.accessToken);
    // Initializing Google Drive and confirming permissions
    GDrive.init();
    // Check if Initialized
    return GDrive.isInitialized();
  };

  const _getAllFilesList = async () => {
    try {
      if (!(await _initGoogleDrive())) {
        return alert('Failed to Initialize Google Drive');
      }
      let data = await GDrive.files.list({
        q: GDrive._stringifyQueryParams(
            {trashed: false}, '', ' and ', true
           ),
      });
      let result = await data.json();
      setListData(result.files);
    } catch (error) {
      console.log('Error->', error);
      alert(`Error-> ${error}`);
    }
    setLoading(false);
  };

  const _getAllMyAppFilesList = async () => {
    try {
      if (!(await _initGoogleDrive())) {
        return alert('Failed to Initialize Google Drive');
      }
      // Create/Get Directory on Google Device
      let directoryId = await GDrive.files.safeCreateFolder({
        name: APP_DIRECTORY,
        parents: ('root'),
      });
      console.log('directoryId -> ', directoryId);
      let data = await GDrive.files.list({
        q:
          GDrive._stringifyQueryParams(
            {
              trashed: false,
              // mimeType: 'application/text'
            },
            '',
            ' and ',
            true,
          ) + ` and '${directoryId}' in parents`,
      });
      let result = await data.json();
      setListData(result.files);
    } catch (error) {
      console.log('Error->', error);
      alert(`Error-> ${error}`);
    }
    setLoading(false);
  };

  const ItemView = ({item}) => {
    return (
      // FlatList Item
      <View style={{padding: 10}}>
        <Text style={styles.item} onPress={() => getItem(item)}>
          File Id: {item.id}
          {'\n'}
          File Name: {item.name}
          {'\n'}
          Mine Type: {item.mimeType}
        </Text>
      </View>
    );
  };

  const ItemSeparatorView = () => {
    return (
      // FlatList Item Separator
      <View
        style={{
          height: 0.5,
          width: '100%',
          backgroundColor: '#C8C8C8',
        }}
      />
    );
  };

  const getItem = (item) => {
    //Function for click on an item
    alert(JSON.stringify(item));
  };

  return (
    <SafeAreaView style={styles.container}>
      <Text style={styles.titleText}>
        Listing of Files from Google Drive
      </Text>
      {route.params.type == 'all' ? null : (
        <Text style={{textAlign: 'center'}}>
          Directory: {APP_DIRECTORY}
        </Text>
      )}
      {loading ? (
        <View style={styles.container}>
          <ActivityIndicator size="large" color="#0000ff" />
        </View>
      ) : (
        <FlatList
          data={listData}
          //data defined in constructor
          ItemSeparatorComponent={ItemSeparatorView}
          //Item Separator View
          renderItem={ItemView}
          keyExtractor={(item, index) => index.toString()}
        />
      )}
      <Text style={styles.footerText}>www.aboutreact.com</Text>
    </SafeAreaView>
  );
};

export default GDFilesListingScreen;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    padding: 10,
  },
  titleText: {
    fontSize: 20,
    fontWeight: 'bold',
    textAlign: 'center',
    padding: 20,
  },
  footerText: {
    fontSize: 16,
    textAlign: 'center',
    color: 'grey',
  },
});

src/googleDrivescreens/GDSingleFileScreen.js

// Store/Retrieve Files on Google Drive using React Native App
// https://aboutreact.com/react-native-google-drive/

// Import React in our code
import React, {useState, useEffect} from 'react';

// Import all the components we are going to use
import {
  SafeAreaView,
  StyleSheet,
  Text,
  View,
  ActivityIndicator,
  FlatList,
} from 'react-native';

// For Google Signin
import {GoogleSignin} from 'react-native-google-signin';
// For Google Drive
import GDrive from 'react-native-google-drive-api-wrapper';

const APP_DIRECTORY = 'AboutReactAppExample';

const GDSingleFileScreen = () => {
  // State Defination
  const (listData, setListData) = useState(());
  const (loading, setLoading) = useState(true);

  useEffect(() => {
    _getAllMyAppFilesList();
  }, ());

  const _initGoogleDrive = async () => {
    // Getting Access Token from Google
    let token = await GoogleSignin.getTokens();
    if (!token) return alert('Failed to get token');
    console.log('res.accessToken =>', token.accessToken);
    // Setting Access Token
    GDrive.setAccessToken(token.accessToken);
    // Initializing Google Drive and confirming permissions
    GDrive.init();
    // Check if Initialized
    return GDrive.isInitialized();
  };

  const _getAllMyAppFilesList = async () => {
    try {
      if (!(await _initGoogleDrive())) {
        return alert('Failed to Initialize Google Drive');
      }
      // Create/Get Directory on Google Device
      let directoryId = await GDrive.files.safeCreateFolder({
        name: APP_DIRECTORY,
        parents: ('root'),
      });
      console.log('directoryId -> ', directoryId);
      let data = await GDrive.files.list({
        q:
          GDrive._stringifyQueryParams(
            {
              trashed: false,
              // mimeType: 'application/text'
            },
            '',
            ' and ',
            true,
          ) + ` and '${directoryId}' in parents`,
      });
      let result = await data.json();
      setListData(result.files);
    } catch (error) {
      console.log('Error->', error);
      alert(`Error-> ${error}`);
    }
    setLoading(false);
  };

  const ItemView = ({item}) => {
    return (
      // FlatList Item
      <View style={{padding: 10}}>
        <Text style={styles.item} onPress={() => getItem(item)}>
          File Id: {item.id}
          {'\n'}
          File Name: {item.name}
          {'\n'}
          Mine Type: {item.mimeType}
        </Text>
      </View>
    );
  };

  const ItemSeparatorView = () => {
    return (
      // FlatList Item Separator
      <View
        style={{
          height: 0.5,
          width: '100%',
          backgroundColor: '#C8C8C8',
        }}
      />
    );
  };

  const getItem = async (item) => {
    if (
      !(
        item.mimeType.match(/text/i) ||
        item.mimeType == 'application/x-javascript' ||
        item.mimeType == 'application/json'
      )
    )
      return alert(
        'Sorry we only deal with the text files, Not in binaries'
      );
    setLoading(true);
    try {
      if (!(await _initGoogleDrive())) {
        return alert('Failed to Initialize Google Drive');
      }
      let result = await GDrive.files.get(item.id, {alt: 'media'});
      if (result.ok) {
        result = await result.text();
        console.log('File Content: ' + result);
        alert('File Content: ' + result);
      }
    } catch (error) {
      alert(error);
      console.log(error);
    }
    setLoading(false);
  };

  return (
    <SafeAreaView style={styles.container}>
      <Text style={styles.titleText}>
        Get any Google Drive File (Text File) Content
      </Text>
      {loading ? (
        <View style={styles.container}>
          <ActivityIndicator size="large" color="#0000ff" />
        </View>
      ) : (
        <FlatList
          data={listData}
          //data defined in constructor
          ItemSeparatorComponent={ItemSeparatorView}
          //Item Separator View
          renderItem={ItemView}
          keyExtractor={(item, index) => index.toString()}
        />
      )}
      <Text style={styles.footerText}>www.aboutreact.com</Text>
    </SafeAreaView>
  );
};

export default GDSingleFileScreen;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    padding: 10,
  },
  titleText: {
    fontSize: 20,
    fontWeight: 'bold',
    textAlign: 'center',
    padding: 20,
  },
  footerText: {
    fontSize: 16,
    textAlign: 'center',
    color: 'grey',
  },
});

src/googleDrivescreens/GDDeleteFileScreen.js

// Store/Retrieve Files on Google Drive using React Native App
// https://aboutreact.com/react-native-google-drive/

// Import React in our code
import React, {useState, useEffect} from 'react';

// Import all the components we are going to use
import {
  SafeAreaView,
  StyleSheet,
  Text,
  View,
  ActivityIndicator,
  FlatList,
  Alert,
} from 'react-native';

// For Google Signin
import {GoogleSignin} from 'react-native-google-signin';
// For Google Drive
import GDrive from 'react-native-google-drive-api-wrapper';

const APP_DIRECTORY = 'AboutReactAppExample';

const GDDeleteFileScreen = () => {
  // State Defination
  const (listData, setListData) = useState(());
  const (loading, setLoading) = useState(true);

  useEffect(() => {
    _getAllMyAppFilesList();
  }, ());

  const _initGoogleDrive = async () => {
    // Getting Access Token from Google
    let token = await GoogleSignin.getTokens();
    if (!token) return alert('Failed to get token');
    console.log('res.accessToken =>', token.accessToken);
    // Setting Access Token
    GDrive.setAccessToken(token.accessToken);
    // Initializing Google Drive and confirming permissions
    GDrive.init();
    // Check if Initialized
    return GDrive.isInitialized();
  };

  const _getAllMyAppFilesList = async () => {
    setLoading(true);
    try {
      if (!(await _initGoogleDrive())) {
        return alert('Failed to Initialize Google Drive');
      }
      // Create/Get Directory on Google Device
      let directoryId = await GDrive.files.safeCreateFolder({
        name: APP_DIRECTORY,
        parents: ('root'),
      });
      console.log('directoryId -> ', directoryId);
      let data = await GDrive.files.list({
        q: GDrive._stringifyQueryParams(
            {trashed: false}, '', ' and ', true) +
          ` and '${directoryId}' in parents`,
      });
      let result = await data.json();
      setListData(result.files);
    } catch (error) {
      console.log('Error->', error);
      alert(`Error-> ${error}`);
    }
    setLoading(false);
  };

  const _deleteDriveData = async (item) => {
    try {
      setLoading(true);
      if (!(await _initGoogleDrive())) {
        return alert('Failed to Initialize Google Drive');
      }
      // Create/Get Directory on Google Device
      let directoryId = await GDrive.files.safeCreateFolder({
        name: APP_DIRECTORY,
        parents: ('root'),
      });
      console.log('directoryId -> ', directoryId);
      let result = await GDrive.files.delete(item.id);
      if (!result.ok) {
        alert('File Deletion Failed');
      }
      _getAllMyAppFilesList();
    } catch (error) {
      alert(error);
      console.log(error);
    }
    setLoading(false);
  };

  const ItemView = ({item}) => {
    return (
      // FlatList Item
      <View style={{padding: 10}}>
        <Text style={styles.item} onPress={() => getItem(item)}>
          File Id: {item.id}
          {'\n'}
          File Name: {item.name}
          {'\n'}
          Mine Type: {item.mimeType}
        </Text>
        <Text style={{color: 'red'}}>Click to Delete</Text>
      </View>
    );
  };

  const ItemSeparatorView = () => {
    return (
      // FlatList Item Separator
      <View
        style={{
          height: 0.5,
          width: '100%',
          backgroundColor: '#C8C8C8',
        }}
      />
    );
  };

  const getItem = (item) => {
    Alert.alert(
      'Warning',
      'Are you sure you want to delete the file from Google Drive?',
      (
        {
          text: 'Yes',
          onPress: () => _deleteDriveData(item),
        },
        {
          text: 'No',
          onPress: () => console.log('No Pressed'),
        },
      ),
      {cancelable: true},
    );
  };

  return (
    <SafeAreaView style={styles.container}>
      <Text style={styles.titleText}>
        Delete any File from Google Drive
      </Text>
      {loading ? (
        <View style={styles.container}>
          <ActivityIndicator size="large" color="#0000ff" />
        </View>
      ) : (
        <FlatList
          data={listData}
          //data defined in constructor
          ItemSeparatorComponent={ItemSeparatorView}
          //Item Separator View
          renderItem={ItemView}
          keyExtractor={(item, index) => index.toString()}
        />
      )}
      <Text style={styles.footerText}>www.aboutreact.com</Text>
    </SafeAreaView>
  );
};

export default GDDeleteFileScreen;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    padding: 10,
  },
  titleText: {
    fontSize: 20,
    fontWeight: 'bold',
    textAlign: 'center',
    padding: 20,
  },
  footerText: {
    fontSize: 16,
    textAlign: 'center',
    color: 'grey',
  },
});

src/googleDrivescreens/GDDownloadFileScreen.js

// Store/Retrieve Files on Google Drive using React Native App
// https://aboutreact.com/react-native-google-drive/

// Import React in our code
import React, {useState, useEffect} from 'react';

// Import all the components we are going to use
import {
  SafeAreaView,
  StyleSheet,
  Text,
  View,
  ActivityIndicator,
  FlatList,
} from 'react-native';

// For Google Signin
import {GoogleSignin} from 'react-native-google-signin';
// For Google Drive
import GDrive from 'react-native-google-drive-api-wrapper';
// To manage local files
import RNFS from 'react-native-fs';

const APP_DIRECTORY = 'AboutReactAppExample';

const GDDownloadFileScreen = () => {
  // State Defination
  const (listData, setListData) = useState(());
  const (loading, setLoading) = useState(true);

  useEffect(() => {
    _getAllMyAppFilesList();
  }, ());

  const _initGoogleDrive = async () => {
    // Getting Access Token from Google
    let token = await GoogleSignin.getTokens();
    if (!token) return alert('Failed to get token');
    console.log('res.accessToken =>', token.accessToken);
    // Setting Access Token
    GDrive.setAccessToken(token.accessToken);
    // Initializing Google Drive and confirming permissions
    GDrive.init();
    // Check if Initialized
    return GDrive.isInitialized();
  };

  const _getAllMyAppFilesList = async () => {
    try {
      if (!(await _initGoogleDrive())) {
        return alert('Failed to Initialize Google Drive');
      }
      // Create/Get Directory on Google Device
      let directoryId = await GDrive.files.safeCreateFolder({
        name: APP_DIRECTORY,
        parents: ('root'),
      });
      console.log('directoryId -> ', directoryId);
      let data = await GDrive.files.list({
        q:
          GDrive._stringifyQueryParams(
            {
              trashed: false,
              // mimeType: 'application/text'
            },
            '',
            ' and ',
            true,
          ) + ` and '${directoryId}' in parents`,
      });
      let result = await data.json();
      setListData(result.files);
    } catch (error) {
      console.log('Error->', error);
      alert(`Error-> ${error}`);
    }
    setLoading(false);
  };

  const ItemView = ({item}) => {
    return (
      // FlatList Item
      <View style={{padding: 10}}>
        <Text style={styles.item} onPress={() => getItem(item)}>
          File Id: {item.id}
          {'\n'}
          File Name: {item.name}
          {'\n'}
          Mine Type: {item.mimeType}
        </Text>
        <Text style={{color: 'red'}}>Click to Download</Text>
      </View>
    );
  };

  const ItemSeparatorView = () => {
    return (
      // FlatList Item Separator
      <View
        style={{
          height: 0.5,
          width: '100%',
          backgroundColor: '#C8C8C8',
        }}
      />
    );
  };

  const getItem = async (item) => {
    if (Platform.OS === 'android') {
      try {
        const granted = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
          {
            title: 'External Storage Write Permission',
            message: 'App needs write permission',
          },
        );
        // If WRITE_EXTERNAL_STORAGE Permission is granted
        if (granted != PermissionsAndroid.RESULTS.GRANTED) return;
      } catch (err) {
        console.warn(err);
        alert('Write permission err', err);
        return;
      }
    }

    try {
      if (!(await _initGoogleDrive())) {
        return alert('Failed to Initialize Google Drive');
      }
      console.log(
        `Destination: ${RNFS.DocumentDirectoryPath}/${item.name}`
      );
      setLoading(true);
      GDrive.files
        .download(item.id, {
          toFile: `${RNFS.DocumentDirectoryPath}/${item.name}`,
          method: 'POST',
          headers: {
            Accept: 'application/json',
          },
        })
        .promise.then((res) => {
          console.log({res});
          setLoading(false);
          if (res.statusCode == 200 && res.bytesWritten > 0)
            alert('File download successful');
        });
    } catch (error) {
      alert(error);
      console.log(error);
      setLoading(false);
    }
  };

  return (
    <SafeAreaView style={styles.container}>
      <Text style={styles.titleText}>
        Download any Google Drive File
      </Text>
      {loading ? (
        <View style={styles.container}>
          <ActivityIndicator size="large" color="#0000ff" />
        </View>
      ) : (
        <FlatList
          data={listData}
          //data defined in constructor
          ItemSeparatorComponent={ItemSeparatorView}
          //Item Separator View
          renderItem={ItemView}
          keyExtractor={(item, index) => index.toString()}
        />
      )}
      <Text style={styles.footerText}>www.aboutreact.com</Text>
    </SafeAreaView>
  );
};

export default GDDownloadFileScreen;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    padding: 10,
  },
  titleText: {
    fontSize: 20,
    fontWeight: 'bold',
    textAlign: 'center',
    padding: 20,
  },
  footerText: {
    fontSize: 16,
    textAlign: 'center',
    color: 'grey',
  },
});

运行 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

输出截图

React_native_google_drive_example1React_native_google_drive_example2React_native_google_drive_example3React_native_google_drive_example4React_native_google_drive_example5

React_native_google_drive_example6

React_native_google_drive_example7React_native_google_drive_example8React_native_google_drive_example9React_native_google_drive_example10

React_native_google_drive_example11

React_native_google_drive_example12

这是您使用 React Native 应用程序在 Google Drive 上存储/检索文件的方法。 如果您有任何疑问或想分享有关该主题的内容,您可以在下面发表评论或在此处联系我们。 很快就会有更多帖子发布。

推荐:如何修复Windows 10/11中的文件系统错误


发表评论