shreyanshu agarwal
shreyanshu agarwal

Reputation: 43

CORS Error on uploading image file to google cloud using signed url

I am getting CORS error while uploading image file to google cloud from localhost using signed url,how to avoid it?

Code To generate signedUrl :

    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 from bucket:

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 Code :

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);

}

Response from google cloud:

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.

Upvotes: 1

Views: 3052

Answers (2)

Rafael Dinov
Rafael Dinov

Reputation: 1

Just add correct header - contentType: 'application/octet-stream'
Example:

const signedUrl = storage.bucket('storage_name')
  .file('folder_name/fileName')
  .getSignedUrl({
    version: 'v4',
    action: 'write',
    expires: Date.now() + 15 * 60 * 1000, //  15 min 
    contentType: 'application/octet-stream',
  });

const uploadHandler = async (signedUrl: string) => {
    try {
      await fetch(url, {
        method: 'PUT',
        body: file,
        headers: {
          'Content-Type': 'application/octet-stream',
        },
      });
    } catch (error) {
      console.log('Error:', error);
    }
  };

Upvotes: 0

shreyanshu agarwal
shreyanshu agarwal

Reputation: 43

I changed the cors file :

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

and it worked

Upvotes: 3

Related Questions