簡體   English   中英

S3 putObject使用AWS-SDK失敗

[英]S3 putObject fails using aws-sdk

這讓我發瘋,任何幫助將不勝感激!

要在S3中設置存儲桶,我遵循了http://www.cheynewallace.com/uploading-to-s3-with-angularjs/

關於此帖子,我通過“通配符”擴展了政策並給予了更多權利,從而在“改進”之后

{
"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/*"
        ]
    }
]
}

並將<ExposeHeader> ETag </ ExposeHeader>添加到存儲桶的Cors設置

然后我使用aws-sdk的角度服務看起來像

/// <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);

為了測試目的,我將imgData編碼為Base64,例如“ / 9j / 4AAQSkZJRgABAgAAZABkA ....”(當然,這是用http://base64-image.de轉換的有效圖像)

結果,每次我嘗試時,都會遇到以下錯誤

{“ line”:25,“ column”:24996,“ sourceURL”:“ http:// localhost:8100 / lib / aws-sdk / dist / aws-sdk.min.js ”,“ message”:“請求我們計算出的簽名與您提供的簽名不匹配。請檢查您的密鑰和簽名方法。“,”代碼“:” SignatureDoesNotMatch“,” region“:null,” time“:” 2016-06-08T15:12:09.945Z“ ,“ requestId”:空,“ statusCode”:403,“ retryable”:false,“ retryDelay”:60.59883770067245}

玩得很盡興...

更新標題:

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

更新資料

即使嘗試上傳非Base64內容,它也會出現相同的錯誤

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

更新#2

我轉移到一個解決方案,該解決方案具有節點js服務器生成的簽名URL(如以下解決方案中所述),但仍然收到與結果相同的錯誤...但是我至少要嘗試;)

使用簽名的URL將文件從angularjs直接上傳到Amazon s3

我終於找到了解決方法,或者至少是解決方法。

在將基於客戶端aws-sdk的客戶端解決方案遷移到服務器生成SignedUrl的解決方案之后,我仍然面臨着同樣的錯誤。 長話短說,它通過在兩邊設置標題的Content-type來解決此問題。

如果某人一天遇到相同問題,我的代碼:

服務器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});
    }
});
});

客戶角度:

  • 首先或當然有一部分可以調用節點服務器,對我的服務器進行明顯的POST

然后第二部分處理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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM