如何从React Native应用程序将文件或图像上传到AWS S3存储桶

如何从React Native应用程序将文件或图像上传到AWS S3存储桶

将文件或图像上传到 AWS S3 存储桶

在这篇文章中,我将向您展示如何从适用于 Android 和 iOS 的 React Native 应用程序将文件/图像上传到 AWS S3 存储桶。 此示例将介绍如何从文件系统中选取任何图像并将其上传到 AWS S3 存储桶。 我没有提到太多关于 AWS s3 设置的事情,因为它是服务器端开发的一部分。

推荐:如何修复Windows应用程序中发生未处理的异常错误

什么是 AWS 和 S3 存储桶?

Amazon Web Services 是 Amazon 的子公司,以按量付费的方式向个人、公司和政府提供按需云计算平台和 API。

Amazon Simple Storage Service (Amazon S3) 是一种对象存储服务,提供业界领先的可扩展性、数据可用性、安全性和性能。 您可以将它用于许多用例,例如

  1. 数据湖
  2. 网站
  3. 移动应用程序
  4. 备份还原
  5. 档案
  6. 企业应用
  7. 物联网设备
  8. 大数据分析

如果您在阅读 S3 定义后还不清楚,您可以想象一个远程硬盘,您可以在其中存储 n 个文件,这些文件可以按照我们用于本地文件存储的相同文件夹方式排列。 如果您使用的是 Windows 操作系统,请将存储桶与计算机的 C、D 或其他驱动器进行比较。

如何设置 Amazon S3 存储桶?

可以使用 Amazon S3 提供的控制台或使用 AWS 开发工具包以编程方式管理存储桶。 您可以按照以下步骤设置 Amazon S3 存储桶

1. 注册 Amazon S3 账户

要使用 S3 存储桶,您首先需要一个 Amazon S3 账户。 要注册,请转至 S3服务页面 并单击“开始使用 Amazon S3”按钮。 为此,您需要一张信用卡/借记卡,但不用担心,亚马逊网络服务在开始的 12 个月内免费,您也可以随时停用您的帐户。

2. 找到您的凭据

要找到您帐户的凭据,您需要:

  • 前往 AWS 管理控制台
  • 将鼠标悬停在右上角菜单中您的个人资料名称上,然后单击“我的安全凭证”
  • 滚动到“访问密钥”部分
  • 点击“创建新的访问密钥”
  • 请注意这两个 访问密钥 IDYOUR_AMAZON_S3_KEY) 和 秘密访问密钥YOUR_AMAZON_S3_SECRET

重要的 出于安全原因,我们建议在生产部署时设置 IAM 用户。 如果您想使用 IAM 用户,那么您需要设置 这些 政策。

3. 创建桶

要创建 S3 存储桶,请使用 S3管理控制台。 我们推荐以下任意一种:

请务必记下您的姓名 桶名称YOUR_AMAZON_S3_BUCKET)创建后。

设置完 Amazon S3 存储桶后,您可以继续操作。

如何将任何文件或图像上传到AWS S3存储桶?

上传我们要使用的图像或文件 react-native-aws3 图书馆。 React Native AWS3 是一个用于将文件上传到 S3 的模块。 与其他库不同,它没有本机依赖项。

它提供了一个简单的 RNS3 具有 put 函数开始上传的组件。

RNS3.put(file, options).then(response => {
  if (response.status !== 201)
    throw new Error("Failed to upload image to S3");
  console.log(response.body);
  /**
   * {
   *   postResponse: {
   *     bucket: "your-bucket",
   *     etag : "9f620878e06d28774406017480a59fd4",
   *     key: "uploads/image.png",
   *     location: "https://your-bucket.s3.amazonaws.com/***.png"
   *   }
   * }
   */
});

要使用 RNS3,我们必须提供文件详细信息

const file = {
  uri: "**Your selected file path**",
  name: "**File name**",
  type: "**File Type**"
}

和选项 accessKeysecretKey

const options = {
  keyPrefix: '**Your Key Prefix**', // Ex. myuploads/
  bucket: '**Name of Your AWS Bucket**', // Ex. aboutreact
  region: '**Region**', // Ex. ap-south-1
  accessKey: '**Replace your Access Key**',
  // Ex. AKIH73GS7S7C53M46OQ
  secretKey: '**Replace your Secrete Key**',
  // Ex. Pt/2hdyro977ejd/h2u8n939nh89nfdnf8hd8f8fd
  successActionStatus: 201,
}

上传到 AWS S3 存储桶示例说明

在此示例中,我们将创建一个带有两个按钮的屏幕。 一个按钮用于从文件系统中选取文件,另一个按钮用于将文件上传到 AWS S3 存储桶。

如果您在图像选择器方面遇到任何挑战,那么您可以查看 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

安装以下依赖项以从图库中选择图像

npm install react-native-image-picker --save

要在 AWS S3 上上传文件,我们需要安装以下依赖项

npm install --save react-native-aws3

CocoaPods 安装

现在我们需要安装 pod

cd ios && pod install && cd ..

IOS 读取存储的权限

1.打开项目 YourProject -> ios -> YourProject.xcworkspace 在 XCode 中。 单击左侧边栏中的“项目”(在我的例子中为 ImagePickerExample),您将在工作区中看到多个选项。

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

Screenshot 2019 02 10 at 11.07.26 AM

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

  • 如果您允许用户从照片中选择图像/视频,请添加“隐私 – 照片库添加使用说明”。
钥匙 价值
隐私 – 照片库添加 使用说明 应用程序需要照片库访问

Screenshot 2019 02 10 at 11.08.25 AM

在 React Native 中将文件上传到 AWS S3 存储桶的代码

在任何代码编辑器中打开 App.js 并将代码替换为以下代码。 请记住在运行代码之前更新以下内容

{
  keyPrefix: '**Your Key Prefix**', // Ex. myuploads/
  bucket: '**Name of Your AWS Bucket**', // Ex. aboutreact
  region: '**Region**', // Ex. ap-south-1
  accessKey: '**Replace your Access Key**',
  // Ex. AKIH73GS7S7C53M46OQ
  secretKey: '**Replace your Secrete Key**',
  // Ex. Pt/2hdyro977ejd/h2u8n939nh89nfdnf8hd8f8fd
  successActionStatus: 201,
}

应用程序.js

// How to Upload any File or Image to AWS S3 Bucket from React Native App
// https://aboutreact.com/react-native-upload-file-to-aws-s3-bucket/

// Import React
import React, {useState} from 'react';
// Import required components
import {
  SafeAreaView,
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  Image,
} from 'react-native';
import {RNS3} from 'react-native-aws3';

import {launchImageLibrary} from 'react-native-image-picker';

const App = () => {
  const (filePath, setFilePath) = useState({});
  const (uploadSuccessMessage, setUploadSuccessMessage) = useState('');

  const chooseFile = () => {
    let options = {
      mediaType: 'photo',
    };
    launchImageLibrary(options, (response) => {
      console.log('Response=", response);
      setUploadSuccessMessage("');
      if (response.didCancel) {
        alert('User cancelled camera picker');
        return;
      } else if (response.errorCode == 'camera_unavailable') {
        alert('Camera not available on device');
        return;
      } else if (response.errorCode == 'permission') {
        alert('Permission not satisfied');
        return;
      } else if (response.errorCode == 'others') {
        alert(response.errorMessage);
        return;
      }
      setFilePath(response);
    });
  };

  const uploadFile = () => {
    if (Object.keys(filePath).length == 0) {
      alert('Please select image first');
      return;
    }
    RNS3.put(
      {
        // `uri` can also be a file system path (i.e. file://)
        uri: filePath.uri,
        name: filePath.fileName,
        type: filePath.type,
      },
      {
        keyPrefix: '**Your Key Prefix**', // Ex. myuploads/
        bucket: '**Name of Your AWS Bucket**', // Ex. aboutreact
        region: '**Region**', // Ex. ap-south-1
        accessKey: '**Replace your Access Key**',
        // Ex. AKIH73GS7S7C53M46OQ
        secretKey: '**Replace your Secrete Key**',
        // Ex. Pt/2hdyro977ejd/h2u8n939nh89nfdnf8hd8f8fd
        successActionStatus: 201,
      },
    )
      .progress((progress) =>
        setUploadSuccessMessage(
          `Uploading: ${progress.loaded / progress.total} (${
            progress.percent
          }%)`,
        ),
      )
      .then((response) => {
        if (response.status !== 201)
          alert('Failed to upload image to S3');
        console.log(response.body);
        setFilePath('');
        let {
          bucket,
          etag,
          key,
          location
        } = response.body.postResponse;
        setUploadSuccessMessage(
          `Uploaded Successfully: 
          \n1. bucket => ${bucket}
          \n2. etag => ${etag}
          \n3. key => ${key}
          \n4. location => ${location}`,
        );
        /**
         * {
         *   postResponse: {
         *     bucket: "your-bucket",
         *     etag : "9f620878e06d28774406017480a59fd4",
         *     key: "uploads/image.png",
         *     location: "https://bucket.s3.amazonaws.com/**.png"
         *   }
         * }
         */
      });
  };

  return (
    <SafeAreaView style={styles.container}>
      <Text style={styles.titleText}>
        How to Upload any File or Image to AWS S3 Bucket{'\n'}
        from React Native App
      </Text>
      <View style={styles.container}>
        {filePath.uri ? (
          <>
            <Image
              source={{uri: filePath.uri}}
              style={styles.imageStyle}
            />
            <Text style={styles.textStyle}>
              {filePath.uri}
            </Text>
            <TouchableOpacity
              activeOpacity={0.5}
              style={styles.buttonStyleGreen}
              onPress={uploadFile}>
              <Text style={styles.textStyleWhite}>
                Upload Image
              </Text>
            </TouchableOpacity>
          </>
        ) : null}
        {uploadSuccessMessage ? (
          <Text style={styles.textStyleGreen}>
            {uploadSuccessMessage}
          </Text>
        ) : null}
        <TouchableOpacity
          activeOpacity={0.5}
          style={styles.buttonStyle}
          onPress={chooseFile}>
          <Text style={styles.textStyleWhite}>
            Choose Image
          </Text>
        </TouchableOpacity>
      </View>
      <Text style={{textAlign: 'center'}}>
        www.aboutreact.com
      </Text>
    </SafeAreaView>
  );
};

export default App;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 10,
    backgroundColor: '#fff',
  },
  titleText: {
    fontSize: 22,
    fontWeight: 'bold',
    textAlign: 'center',
    paddingVertical: 20,
  },
  textStyle: {
    padding: 10,
    color: 'black',
    textAlign: 'center',
  },
  textStyleGreen: {
    padding: 10,
    color: 'green',
  },
  textStyleWhite: {
    padding: 10,
    color: 'white',
  },
  buttonStyle: {
    alignItems: 'center',
    backgroundColor: 'orange',
    marginVertical: 10,
    width: '100%',
  },
  buttonStyleGreen: {
    alignItems: 'center',
    backgroundColor: 'green',
    marginVertical: 10,
    width: '100%',
  },
  imageStyle: {
    flex: 1,
    width: '100%',
    height: '100%',
    resizeMode: 'contain',
    margin: 5,
  },
});

运行 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_aws_s3_upload1 React_native_aws_s3_upload2 React_native_aws_s3_upload3 React_native_aws_s3_upload4 React_native_aws_s3_upload5 React_native_aws_s3_upload6

这是如何从 React Native 应用程序将文件或图像上传到 AWS S3 存储桶。 如果您有任何疑问或想分享有关该主题的内容,您可以在下面发表评论或在此处联系我们。 很快就会有更多帖子发布。 敬请关注!

推荐:使用PouchDB和CouchDB在React Native中构建离线应用程序


发表评论