如何使用axios将文件上传到amazon s3 bucket?

时间:2017-08-15 05:17:13

标签: reactjs amazon-s3 amazon axios

首先,我是非常新的反应。我正在尝试使用axios将文件上传到我的亚马逊S3存储桶。 我正确地获得了签名网址,但我不知道如何继续..我试过这个,但它不起作用。

我得到的错误如下: 跨源请求已阻止:同源策略禁止在https://xxx.s3.amazonaws.com/wolves.jpeg?AWSAccessKeyId=xxxxxxxxxx&Content-Type=image%2Fjpeg&Expires=1502773987&Signature=ZXQya8d3xZoikzX6dIbdL3Bvb8A%3D读取远程资源。 (原因:缺少CORS标题'Access-Control-Allow-Origin'。

import React, { Component } from 'react'
import Dropzone from 'react-dropzone'
import aws from 'aws-sdk'
import axios from 'axios'

export default class ImageAWS extends Component{

    uploadFile(files){

        console.log('uploadFile: ')
        const file = files[0]

        aws.config.update({
            accessKeyId: 'xxxxxxxxx',
            secretAccessKey: 'xxxxxxxx'
        });

        var s3 = new aws.S3();

        var params = {
        Bucket: 'xxx',
        Key: file.name,
        Expires: 60,
        ContentType: file.type
    };

    s3.getSignedUrl('putObject', params, function(err, signedUrl) {
        if (err) {
            console.log(err);
            return err;
        } else {
            console.log(signedUrl);

            var instance = axios.create();

            instance.put(signedUrl, file, {headers: {'Content-Type': file.type}})
                .then(function (result) {
                    console.log(result);
                })
                .catch(function (err) {
                    console.log(err);
                });
            return signedUrl;
        }
    });

}

render () {
    return (
        <div>
            Images Component
            <Dropzone onDrop={this.uploadFile.bind(this)} />
        </div>

    )
}

}

OPTIONS https://xxbucket.s3.amazonaws.com/wolves.jpeg?
AWSAccessKeyId=xxxxxxxxxxxxxxxxxx&Content-Type=image%2Fjpeg&Expires=1502894764&Signature=FqAccUimhyrLgLBldVy%2Fkyx2Xmc%3D HTTP/1.1

Host: xxbucket.s3.amazonaws.com

User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:54.0) Gecko/20100101 
Firefox/54.0

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

Accept-Language: en-US,en;q=0.5

Accept-Encoding: gzip, deflate, br

Access-Control-Request-Method: PUT

Access-Control-Request-Headers: access-control-allow-headers,access-control-allow-methods,access-control-allow-origin

Origin: http://localhost:8080

Connection: keep-alive





HTTP/1.1 403 Forbidden

x-amz-request-id: 4282B87BA935EF9A

x-amz-id-2: jWOwOQ/7BCzvw1xPmJroOzUBhbCmpfGx5HCPaPUvMoYTFMrlhoG5wN902B1brZ5cjYnKHMLWmpQ=

Content-Type: application/xml

Date: Wed, 16 Aug 2017 14:45:05 GMT

Server: AmazonS3

Content-Length: 514



  <?xml version="1.0" encoding="UTF-8"?>
 <Error><Code>AccessForbidden</Code><Message>CORSResponse: This CORS request is not allowed. This is usually because the evalution of Origin, request method / Access-Control-Request-Method or Access-Control-Request-Headers are not whitelisted by the resource's CORS spec.</Message><Method>PUT</Method><ResourceType>OBJECT</ResourceType><RequestId>4282B87BA935EF9A</RequestId><HostId>jWOwOQ/7BCzvw1xPmJroOzUBhbCmpfGx5HCPaPUvMoYTFMrlhoG5wN902B1brZ5cjYnKHMLWmpQ=</HostId></Error>

1 个答案:

答案 0 :(得分:1)

您需要将所需的CORS标头添加到您的开发服务器。 Read about CORS。根据您的开发服务器,搜索添加响应标头的正确方法。然后,将以下标头添加到每个响应中:

"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
"Access-Control-Allow-Headers": "X-Requested-With, content-type, Authorization"

这将允许从网络上的其他网站请求数据。确保只将它们添加到开发版本中(我假设您正在学习,所以没关系)。在制作时,您需要将“Access-Control-Allow-Origin”:“*”限制为特定网址。

进一步阅读: