如何使用React和Amplify与S3交互

时间:2019-06-17 05:31:28

标签: reactjs amazon-s3

本质上,我正在使用React和Amplify开发文件托管Web应用程序,并且已经通过身份验证等工作,但始终坚持如何在存储桶中列出文件,上传和下载。

我研究了扩增文档,但对此感到困惑。

1 个答案:

答案 0 :(得分:0)

您好@SpotlessThoughtful欢迎使用StackOverflow

以下指南介绍了how to setup & configure your React application with AWS Amplify

概述

  1. 在Cognito中配置S3权限
  2. 设置放大
  3. 使用存储子模块
  4. 设置S3存储桶

我很确定它将帮助您澄清您的任何疑问。


指南的重点

使用AWS Amplify将图像上传到S3的示例:

创建一个services.js文件,并包含以下功能:

import Amplify from '@aws-amplify/core';
import Storage from '@aws-amplify/storage';

export function configureAmplify() {
  Amplify.configure(
  {
   Auth: {
     identityPoolId: process.env.REACT_APP_identityPoolId,
     region: process.env.REACT_APP_region,
     userPoolId: process.env.REACT_APP_userPoolId,
     userPoolWebClientId: process.env.REACT_APP_userPoolWebClientId,
    },
  Storage: { 
     bucket: process.env.REACT_APP_Bucket_name,
     region: process.env.REACT_APP_region,
     identityPoolId: process.env.REACT_APP_identityPoolId
    }
  }
 );
}

//Configure Storage with S3 bucket information
export function SetS3Config(bucket, level){
   Storage.configure({ 
          bucket: bucket,
          level: level,
          region: 'us-east-1',  
          identityPoolId: process.env.REACT_APP_identityPoolId 
       });
}

在您的index.js文件中:

import React, { Component } from "react";
import ReactDOM from "react-dom";
import { configureAmplify, SetS3Config } from "./services";
import Storage from "@aws-amplify/storage";
import "./styles.css";

class App extends Component {
  state = {
    imageName: "",
    imageFile: "",
    response: ""
  };

  uploadImage = () => {
    SetS3Config("my-test-bucket-amplify", "protected");
    Storage.put(`userimages/${this.upload.files[0].name}`,
                this.upload.files[0],
                { contentType: this.upload.files[0].type })
      .then(result => {
        this.upload = null;
        this.setState({ response: "Success uploading file!" });
      })
      .catch(err => {
        this.setState({ response: `Cannot uploading file: ${err}` });
      });
  };

  render() {
    return (
      <div className="App">
        <h2>S3 Upload example...</h2>
        <input
          type="file"
          accept="image/png, image/jpeg"
          style={{ display: "none" }}
          ref={ref => (this.upload = ref)}
          onChange={e =>
            this.setState({
              imageFile: this.upload.files[0],
              imageName: this.upload.files[0].name
            })
          }
        />
        <input value={this.state.imageName} placeholder="Select file" />
        <button
          onClick={e => {
            this.upload.value = null;
            this.upload.click();
          }}
          loading={this.state.uploading}
        >
          Browse
        </button>

        <button onClick={this.uploadImage}> Upload File </button>

        {!!this.state.response && <div>{this.state.response}</div>}
      </div>
    );
  }
}

configureAmplify();
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);