How to upload file to amazon s3 bucket using axios?

10,588

Solution 1

You'll need to add the required CORS headers to your dev server. Read about CORS. Depending on your development server, search for the proper way to add response headers. Then, add the following headers to every response:

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

This will enable to request data from other websites on the web. Make sure you add them to the development version only(I assume you are learning, so that's OK). On production, you'll need to limit the "Access-Control-Allow-Origin": "*", to specific urls.

Further reading:

Solution 2

For those who are facing this issue while uploading files from front end, Go to AWS S3 -> select your bucket -> permission tab -> scroll to last

Under section Cross-origin resource sharing (CORS), edit and drop your configuration

[
    {
        "AllowedHeaders": [
            "Authorization",
            "Content-Range",
            "Accept",
            "Content-Type",
            "Origin",
            "Range",
            "Access-Control-Allow-Origin"
        ],
        "AllowedMethods": [
            "GET",
            "PUT"
        ],
        "AllowedOrigins": [
            "*"
        ],
        "ExposeHeaders": [
            "Content-Range",
            "Content-Length",
            "ETag"
        ],
        "MaxAgeSeconds": 3000
    }
]

You can edit this as per your requirements.

Finally, Publish/Save it.

This will resolve your CORS issue.

Share:
10,588

Related videos on Youtube

Marcus
Author by

Marcus

Updated on June 04, 2022

Comments

  • Marcus
    Marcus almost 2 years

    first of all, I am very very new to react. I am trying to upload a file to my amazon S3 bucket using axios. I get the signature url correctly but I don't know how to continue.. I tried this but it doesn't work.

    The error I get is the following: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://xxx.s3.amazonaws.com/wolves.jpeg?AWSAccessKeyId=xxxxxxxxxx&Content-Type=image%2Fjpeg&Expires=1502773987&Signature=ZXQya8d3xZoikzX6dIbdL3Bvb8A%3D. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

    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>
    
  • Marcus
    Marcus over 6 years
    Thanks for your answer. I've added the headers to webpack but it still doesn't work. I get the same error message.
  • Some1Else
    Some1Else over 6 years
    Can you supply full http session recording(with headers & body)? you can use fiddler2 for that.
  • Marcus
    Marcus over 6 years
    I made it work, It was not something about my code. It was about CORS properties in s3 bucket. I had <AllowedHeader>Authorization</AllowedHeader> and <AllowedHeader>*</AllowedHeader> fixed it. Thank you again.