user1031143
user1031143

Reputation: 828

Upload file to google cloud storage by javascript

I'm trying to upload files to my own buckets by PUT method but couldn't get it to work:

function upload(url, data) {
    var pd = new XMLHttpRequest();
    pd['open']('PUT', "http://storage.googleapis.com/" + url, true);
    pd['setRequestHeader']('Content-type', 'text/html');
    pd['setRequestHeader']('x-goog-acl', 'public-read');
    pd['setRequestHeader']('Authorization', 'Bearer *********F0aIu4NbTd6A');
    pd['setRequestHeader']('Content-length', data['length']);
    pd['setRequestHeader']('Connection', 'close');
    pd['send'](data);
}
upload('bucked/index.html','<b>hello</b>');

Upvotes: 1

Views: 3128

Answers (3)

sratatata
sratatata

Reputation: 55

I had similar problem:

request.setRequestHeader('x-goog-acl', 'public-read');
request.setRequestHeader('Authorization', 'Bearer ' + access_token);
request.setRequestHeader("X-File-Name", file.name);
request.setRequestHeader("X-File-Size", file.size);.
  1. set proper origin
  2. add response header (same as in your request) ["authorization", "content-type", "x-file-name", "x-file-size", "x-goog-acl"]
  3. PUT and OPTIONS methods I found solution on this doc

sample cors.json

[
    {
        "origin": ["*", "http://localhost:8080", "https://localhost:8080"],
        "responseHeader": ["authorization", "content-type", "x-file-name", "x-file-size", "x-goog-acl"],
        "method": ["GET", "HEAD", "DELETE", "PUT", "OPTIONS"],
        "maxAgeSeconds": 3600
    }
]

To set this configuration use gsutil cors set cors.json gs://your_bucket

PS. Connection and Content-lenght are not necessary, JS would throw some errors to Console.

Upvotes: 2

Navneet
Navneet

Reputation: 141

The error seems to indicate that CORS is not set up for your bucket.

Upvotes: 2

maldred
maldred

Reputation: 84

It would be more helpful if you could tell us how the PUT operation is failing. Have you tried uploading to commondatastorage.googleapis.com rather than storage.googleapis.com?

Upvotes: 0

Related Questions