简体   繁体   中英

S3 putObject fails using aws-sdk

It's driving me crazy, any help would be much appreciated!

To set up my bucket in S3 I followed http://www.cheynewallace.com/uploading-to-s3-with-angularjs/

Regarding this post I made following "improvements" by extended the policy with a wildcard and giving more rights

{
"Version": "2012-10-17",
"Statement": [
    {
        "Effect": "Allow",
        "Action": [
            "s3:DeleteObject",
            "s3:DeleteObjectVersion",
            "s3:GetObject",
            "s3:GetObjectAcl",
            "s3:GetObjectTorrent",
            "s3:GetObjectVersion",
            "s3:GetObjectVersionAcl",
            "s3:GetObjectVersionTorrent",
            "s3:PutObject",
            "s3:PutObjectAcl",
            "s3:PutObjectVersionAcl"
        ],
        "Resource": [
            "arn:aws:s3:::photos-eu/*"
        ]
    }
]
}

and added < ExposeHeader>ETag< /ExposeHeader > to the Cors settings of the bucket

Then my angular service using the aws-sdk look like

/// <reference path="../../../typings/tsd.d.ts" />

module Services {

  export interface IS3UploadService {
    upload(imgName:string, imgData:string):ng.IPromise<{}>;
  }

  export class S3UploadService implements IS3UploadService {

static $inject = ['$q'];

private bucket:AWS.S3;

constructor(private $q:ng.IQService) {
  var credentials = new AWS.Credentials("myAccessKeyId", "mySecretAccessKey");
  AWS.config.update(credentials);
  AWS.config.region = "eu-west-1";

  this.bucket = new AWS.S3({params: {Bucket: 'peterparker-photos-eu', maxRetries: 10, region: "eu-west-1"}});

}

upload(imgName:string, imgData:string):ng.IPromise<{}> {
  var deferred = this.$q.defer();

  var params:AWS.s3.PutObjectRequest = {
    Bucket: "peterparker-photos-eu",
    Key: imgName,
    Body: imgData,
    ContentType: "image/jpeg",
    ContentEncoding: "Base64"
  };

  this.bucket.putObject(params, (err:any, data:any) => {
    if (err) {
      console.error("->" + JSON.stringify(err));
      deferred.reject(err);
    } else {
      console.info(data);
      deferred.resolve(data);
    }
  });

  return deferred.promise;
}

  }
}

angular.module('App')
  .service('S3UploadService', Services.S3UploadService);

For my test purpose, I push in the imgData an img encoded as Base64, something like "/9j/4AAQSkZJRgABAgAAZABkA...." (of course a valid image converted with http://base64-image.de )

And as result, each time I try, I've got following error

{"line":25,"column":24996,"sourceURL":" http://localhost:8100/lib/aws-sdk/dist/aws-sdk.min.js ","message":"The request signature we calculated does not match the signature you provided. Check your key and signing method.","code":"SignatureDoesNotMatch","region":null,"time":"2016-06-08T15:12:09.945Z","requestId":null,"statusCode":403,"retryable":false,"retryDelay":60.59883770067245}

So much fun...

Update headers:

General
Request URL:https://peterparker-photos-eu.s3-eu-west-1.amazonaws.com/1465408512724.jpg
Request Method:PUT
Status Code:403 Forbidden
Remote Address:54.231.131.16:443

Response headers
Access-Control-Allow-Methods:HEAD, GET, PUT, POST, DELETE
Access-Control-Allow-Origin:*
Access-Control-Expose-Headers:ETag, x-amz-meta-custom-header
Connection:close
Content-Type:application/xml
Date:Wed, 08 Jun 2016 17:55:20 GMT
Server:AmazonS3
Transfer-Encoding:chunked
Vary:Origin, Access-Control-Request-Headers, Access-Control-Request-        Method
x-amz-id-...
x-amz-request-id:...

Request Headers
Accept:*/*
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4,de;q=0.2
Authorization:AWS ...
Connection:keep-alive
Content-Encoding:Base64
Content-Length:38780
Content-MD5:...
Content-Type:image/jpeg; charset=UTF-8
Host:peterparker-photos-eu.s3-eu-west-1.amazonaws.com
Origin:http://localhost:8100
Referer:http://localhost:8100/?ionicplatform=ios
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5)             AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36
X-Amz-Date:Wed, 08 Jun 2016 17:55:20 GMT
X-Amz-User-Agent:aws-sdk-js/2.3.18

Request payload
Img base64 code

Update

Even by trying to upload a non Base64 content it finish with the same error

var paramsHtml:AWS.s3.PutObjectRequest = {
    Bucket: "peterparker-photos-eu",
    Key: "HelloWorld.html",
    Body: "The Body",
    ContentType: "text/html"
  };

Update #2

I moved to a solution with a signed URL generated by my node js server as described in following solution, still got the same error as result...but I least I try ;)

upload file from angularjs directly to amazon s3 using signed url

Freak I finally find the solution or at least a solution.

After migrating my client aws-sdk based solution to a solution where the server generate a signedUrl I was still facing the same error. Short story long, it fixed the problem by setting in both side the Content-type for the header.

My code if someone face the same problem one day:

Server Node.js

var AWS = require('aws-sdk');

AWS.config.update({accessKeyId: "myKey", secretAccessKey: "mySecret"});
AWS.config.region = 'eu-west-1';

app.post('/api/images', securityPolicy.authorise, function (req, res) {

var s3 = new AWS.S3();

var imgName = req.body.imgName;
var contentType = req.body.contentType;

// Expires in seconds
var params = {Bucket: 'photos-eu', Key: imgName, Expires: 600, ContentType: contentType};
s3.getSignedUrl('putObject', params, function (err, url) {
    if (err) {
        res.status(500).json({
            error: "Presigned S3 url for putObject can't be created. " + JSON.stringify(err)
        });
    } else {
        res.json({url: url});
    }
});
});

Client angular:

  • First or course there is the part to call the node server, obvious POST to my server

And then the second part processing the signedURL

private uploadToS3(preSignedUrl:string, imgData:string):ng.IPromise<{}> {
  var deferred = this.$q.defer();

  // Post image to S3
  this.$http({
    method: 'PUT',
    url: preSignedUrl,
    headers: {'Content-Type': 'image/jpeg'},
    data: imgData
  })
    .then((response:any) => {
      console.log("Image uploaded to S3" + JSON.stringify(response));

      deferred.resolve();

    }, (response:any) => {
      console.log("Error Presigned URL" + JSON.stringify(response));
      deferred.reject(response);
    });

  return deferred.promise;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM