CORS使用签名url将图像文件上传到谷歌云时出错



我在使用签名url从本地主机上传图像文件到谷歌云时遇到CORS错误,如何避免?

生成签名Url:的代码

function get_v4_signed_url($bucket, $keyname, $contentType){
$bucket = $this->storageClient->bucket($bucket);
$object = $bucket->object($keyname);
$url = $object->signedUrl(
# This URL is valid for 15 minutes
new DateTime('120 min'),
[
'method' => 'PUT',
'contentType' => $contentType,
'version' => 'v4',
"Access-Control-Allow-Origin" => "*"
]
);
return $url;
}

铲斗CORS:

gsutil cors get gs://bucket-name
[{"maxAgeSeconds": 3600, "method": ["GET", "POST", "PUT", "DELETE", "OPTIONS"], "origin": ["https://localhost:8443"], "responseHeader": ["goog-resumable", "Content-Type", "Authorization", "Content-Length", "User-Agent", "x-goog-resumable"]}]

Javascript代码:

uploadFileToGcp(file, url) {
var xhr  = new XMLHttpRequest();
xhr.open('PUT', url);
xhr.setRequestHeader('Content-Type', file.type);
xhr.setRequestHeader("Access-Control-Allow-Origin","*");
xhr.onload = function () {
var res = JSON.parse(xhr.responseText);
console.log("res: "+res);
if (xhr.status == "200") {
hideLoadingDiv()
console.table(res);
} else {
console.error(res);
}
}
xhr.send(file);
}

谷歌云的回应:

Access to XMLHttpRequest at 'signed_URL' from origin 'https://localhost:8443' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

我更改了cors文件:

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

它起到了的作用

最新更新