在Google Cloud Bucket上上传图片时发生CORS错误

时间:2019-11-21 14:08:30

标签: google-cloud-storage

我正在尝试将图像直接从浏览器上传到Google Cloud存储桶。我在后端使用gcs-signed-urls,并遵循this示例。

这是我的表格上传,效果很好。

<form action={"https://" +this.state.imageForm.bucket +".storage.googleapis.com"}  method="post" enctype="multipart/form-data">
<input type="hidden" name="key" value={this.state.imageForm.key}></input>
<input type="hidden" name="bucket" value={this.state.imageForm.bucket}></input>
<input type="hidden" name="GoogleAccessId" value={this.state.imageForm.GoogleAccessId}></input>
<input type="hidden" name="policy" value={this.state.imageForm.policy}></input>
<input type="hidden" name="signature" value={this.state.imageForm.signature}></input>
<input type="hidden" name="Content-Type" value={this.state.imageForm.contenttype}></input>
<input name="file" type="file"></input>
<input type="submit" value="Upload"></input>

现在,我正在尝试使用Axios将其转换为表单发布请求。

 let data = new FormData();
data.append("key",this.state.imageForm.key+ "." + picture[0].type.replace("image/", ""))
data.append("bucket", this.state.imageForm.bucket);
data.append("GoogleAccessId", this.state.imageForm.GoogleAccessId);
data.append("policy", this.state.imageForm.policy);
data.append("Content-Type", 'application/octet-stream');
data.append("file", picture[0]);
console.log("data", data);
let config = {
  headers: {
    'Content-Type': 'multipart/form-data',
    'Access-Control-Allow-Origin': '*',
  }
}
let result = await axios.post("https://" + this.state.imageForm.bucket + ".storage.googleapis.com",
  data, config)

我遇到2个错误:

1-CROS错误

create:1 Access to XMLHttpRequest at 'https://ccc.storage.googleapis.com/' from origin 'http://127.0.0.1:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

2-发布请求失败,响应为400错误。

这是开发者控制台中的快照。

enter image description here

我还为我的存储桶更新了Cors文件,这是配置

  {
  "origin": [*],
  "responseHeader": ["Content-Type", "access-control-allow-origin"],
  "method": ["GET", "HEAD", "DELETE", "PUT", "POST"],
  "maxAgeSeconds": 3600
}

1 个答案:

答案 0 :(得分:0)

我在API POST method docs

中发现了以下注释
  

注意:POST对象方法不支持signed URLs,除非是resumable uploads

因此,您可以尝试PUT method或按照文档中的说明进行resumable upload