【发布时间】:2017-02-25 14:38:30
【问题描述】:
实际测试用例代码: https://github.com/HenrikJoreteg/google-cloud-signedurl-test-case
我正在尝试为我的 API 添加返回签名 URL 以从客户端直接上传到 Google Cloud Storage 的功能。
服务器端,我为此使用gcloud SDK:
const gcloud = require('gcloud')
const gcs = gcloud.storage({
projectId: 'my project',
keyFilename: __dirname + '/path/to/JSON/file.json'
})
const bucket = gcs.bucket('bucket-name')
bucket.file('IMG_2540.png').getSignedUrl({
action: 'write',
expires: Date.now() + 60000
}, (error, signedUrl) => {
if (error == null) {
console.log(signedUrl)
}
})
然后在浏览器中我有一个<input type='file'/>,我已经选择了一个文件,然后我尝试将它发布到从我的服务器端脚本生成的 URL,如下所示:
function upload(blobOrFile, url) {
var xhr = new XMLHttpRequest();
xhr.open('PUT', url, true);
xhr.onload = function(e) {
console.log('DONE!')
};
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
console.log((e.loaded / e.total) * 100)
}
};
xhr.send(blobOrFile);
}
// grab the `File` object dropped (which incidentally
// matches the file name used when generating the signed URL
upload($('[name=file]').files[0], 'URL GENERATED FROM SERVER-SIDE SCRIPT HERE');
会发生什么?
回复是:
<Error>
<Code>SignatureDoesNotMatch</Code>
<Message>The request signature we calculated does not match the signature you provided. Check your Google secret key and signing method.</Message>
<StringToSign>PUT
image/png
1476631908
/bucket-name/IMG_2540.png</StringToSign>
</Error>
我重新下载了 JSON 密钥文件,以确保它是最新的并且对该存储桶具有适当的权限,并且在生成签名 URL 时我没有收到任何错误或任何东西。
客户端代码似乎可以正确启动上传(我看到进度更新已注销)然后我收到上面的 403 错误。文件名匹配,内容类型似乎与预期值匹配,过期似乎是合理的。
官方SDK生成了URL,所以看起来没问题。
我被困住了,感谢任何帮助。
【问题讨论】:
-
我知道你说内容类型似乎符合预期。不过,要确认的是,当您查看从浏览器发送的标头时,它只是 content-type: image/png ? XHR 为你做这件事,你不需要 setRequestHeader()?
-
谢谢@glenschler,但是,我相信,XHR 从第 2 版开始就可以做到这一点。这是标题:cloudup.com/cWxNOTCs_EZ
-
已更新以包含带有独立案例的 repo:github.com/HenrikJoreteg/google-cloud-signedurl-test-case
标签: javascript node.js google-cloud-storage