基于AWS in Browser-Based Uploads Using POST文档,我试图将音频文件上传到存储桶中,而不必引入整个SDK。我正在使用 Vue.js 。当我发出请求时,这是我返回的错误:
<Error> <Code>InvalidRequest</Code> <Message>The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256.</Message> <RequestId>7FE397A138CF89</RequestId> <HostId>rEx4jk6vj363wlVGrGqutyDkMNeUhi6DizAXhAiIWrIpG8Rups1rLFGO4Dge5loeNj</HostId> </Error>
创建政策,签名密钥和签名的代码
策略功能-创建条件的JSON obj并返回Utf-8和Base64编码的版本(根据AWS Doc's)
getPolicy (date) {
let moment = this.$moment(date) // using moment.js
let formattedDate = moment.format('YYYYMMDD')
let obj = {
"expiration": date,
"conditions": [
{"bucket": "test-bucket"},
{"acl": "public-read"},
{"key": "test.mp3"},
["starts-with", "$Content-Type", "audio/"],
["content-length-range", 1048579, 3000000000],
{"x-amz-server-side-encryption": "AES256"},
{"x-amz-credential": `KJIAI4OQHKZGIBSQY5TQ/${formattedDate}/us-east-2/s3/aws4_request`},
{"x-amz-algorithm": "AWS4-HMAC-SHA256"},
{"x-amz-date": formatedDate}
]
}
let string = JSON.stringify(obj)
let utf8 = encodeURI(string)
let base64 = btoa(utf8)
return base64
}
签名密钥功能-创建HmacSHA256签名密钥(根据AWS Doc's)
getSigningKey (date) {
// AWSSecretAccessKeyId (obviously this is a dummy)
let key = '+eo98jdkXTjOYO2weY84m2vzCV63vMI6yGvC097R'
let dateKey = crypto.HmacSHA256(date, `AWS4${key}`)
let dateRegionKey = crypto.HmacSHA256('us-east-2', dateKey)
let dateRegionServiceKey = crypto.HmacSHA256('s3', dateRegionKey)
let signingKey = crypto.HmacSHA256('aws4_request', dateRegionServiceKey)
return signingKey.toString()
}
签名功能-创建十六进制编码的HmacSHA256签名(根据AWS Doc's)
getSignature (date) {
let policy = this.getPolicy(date)
let signingKey = this.getSigningKey(date)
let signature = crypto.HmacSHA256(policy, signingKey)
let hexEncodedSignature = signature.toString(hex)
return hexEncodedSignature
}
使用AXIOS进行AJAX请求
uploadFile (file) {
const date = new Date().toISOString()
let moment = this.$moment(date)
let formattedDate = b.format('YYYYMMDD')
const policy = this.getPolicy(date)
const signature = this.getSignature(date)
const form = new FormData()
form.append('key', 'test.mp3')
form.append('acl', 'public-read')
form.append('Content-Type', 'audio/*')
form.append('x-amz-server-side-encryption', 'AES256')
form.append('X-Amz-Credential', `KJIAI4OQHKZGIBSQY5TQ/${formattedDate}/us-east-2/s3/aws4_request`)
form.append('X-Amz-Algorithm', 'AWS4-HMAC-SHA256')
form.append('X-Amz-Date', formattedDate)
form.append('AWSAccessKeyId', 'KJIAI4OQHKZGIBSQY5TQ')
form.append('Policy', policy)
form.append('Signature', signature)
form.append('file', file)
return axios.post('https://test-bucket.s3.us-east-2.amazonaws.com/', form).then((response) => {
// do something
}
我该怎么办才能收到响应错误?