无法使用React Native使用AWS S3上传或获取任何文件

时间:2019-09-03 08:24:57

标签: react-native amazon-s3 aws-amplify

我使用AWS S3作为文件存储,但无法上传或从存储桶中获取任何文件。这是我的代码,有人可以帮助我解决此问题。我正在AWSS3Provider - error uploading AccessDenied: Access Denied

这是我的代码:

import React from 'react';
import {SafeAreaView, Text, TouchableOpacity, View,} from 'react-native';
import Amplify, {Storage} from 'aws-amplify';
import {awsmobile} from "./aws-exports";

Amplify.configure(awsmobile);

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {};
    }

    async callerFn() {
        try {
            let file = 'My upload text';
            let name = 'myFile.txt';
            const access = {level: "public"}; // note the access path
            await Storage.put(name, file, access);
        } catch (e) {
            console.log(e.message)
        }
    }

    render() {
        return (
            <View>
                <SafeAreaView>
                    <TouchableOpacity onPress={() => this.callerFn()}>
                        <Text>Press to Upload</Text>
                    </TouchableOpacity>
                </SafeAreaView>
            </View>
        );
    }
}

export default App;

我已为我使用的用户授予所有权限。 这是我的存储桶策略:

{
    "Id": "PolicyXXXXXXXXXXXXX",
    "Version": "2012-10-17",
    "Statement": [
      {
        "Sid": "StmtXXXXXXXXXXXXX",
        "Action": [
          "s3:*"
        ],
        "Effect": "Allow",
        "Resource": "arn:aws:s3:::experimental/*",
        "Principal": {
          "AWS": [
            "arn:aws:iam::XXXXXXXXXXXX:user/amplify-XXXXX"
          ]
        }
      }
    ]
  }

1 个答案:

答案 0 :(得分:0)

我从没有尝试过aws-amplify

解决方案

但是我确实在我的应用程序上使用AWS S3来上传和下载文件。确保根据自述文件设置正确的 IAM策略

这是我使用react-native-aws3

的方法
import { RNS3 } from 'react-native-aws3';

const file = {
  // `uri` can also be a file system path (i.e. file://)
  uri: "assets-library://asset/asset.PNG?id=655DBE66-8008-459C-9358-914E1FB532DD&ext=PNG",
  name: "image.png",
  type: "image/png"
}

const options = {
  keyPrefix: "uploads/",
  bucket: "your-bucket",
  region: "us-east-1",
  accessKey: "your-access-key",
  secretKey: "your-secret-key",
  successActionStatus: 201
}

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/uploads%2Fimage.png"
   *   }
   * }
   */
});