【问题标题】:Create signed URLs for Google Cloud Storage with node.js for direct upload from browser使用 node.js 为 Google Cloud Storage 创建签名 URL,以便从浏览器直接上传
【发布时间】: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


【解决方案1】:

正如菲利普·罗伯茨(Philip Roberts)所指出的,我的 github 存储库中的 @LatentFlip 也包含此案例,在签名中添加内容类型就可以解决问题。

https://github.com/HenrikJoreteg/google-cloud-signedurl-test-case/pull/1/commits/84290918e7b82dd8c1f22ffcd2c7cdc06b08d334

此外,听起来 Google 人员将更新 docs/error 以提供更多帮助:https://github.com/GoogleCloudPlatform/google-cloud-node/issues/1695

【讨论】:

  • 嘿,我也有同样的问题。我克隆了你的仓库,但它不起作用。你能帮我解决这个问题吗?
猜你喜欢
  • 1970-01-01
  • 2020-11-20
  • 2014-01-12
  • 1970-01-01
  • 1970-01-01
  • 2016-06-15
  • 2017-09-16
  • 2018-01-28
  • 1970-01-01
相关资源
最近更新 更多