Reputation: 3220
We're using signed urls to upload from the browser. I haven't been able to figure out how to set the cache-control header while uploading.
We're using the gcloud-node library to sign urls:
var bucket = gcs.bucket('mybucket');
var file = bucket.file('image.jpg');
var expireDate = new Date
expireDate.setDate(expireDate.getDate() + 1);
file.getSignedUrl({
action: 'write',
expires: expireDate,
contentType: 'image/jpeg'
}, function (err, signedUrl) {
if (err) {
console.error('SignedUrl error', err);
} else {
console.log(signedUrl);
}
});
How do I set the Cache-Control headers while uploading a file to GCS?
The code to upload is running in the browser:
var signedUrl = ...; // get from nodejs server
var fileList = this.files;
var file = fileList[0];
jQuery.ajax({
url: signedUrl,
type: 'PUT',
data: file,
processData: false,
contentType: 'image/jpeg'
})
Upvotes: 4
Views: 2531
Reputation: 3091
This is possible, but the documentation is terrible. First you need to setup CORS on the bucket you're uploading to with:
gsutil cors set cors.json gs://bucket-name
Where cors.json
contains something like:
[{
"maxAgeSeconds": 3600,
"method": ["GET", "PUT", "POST"],
"origin": [
"http://localhost:3000"
],
"responseHeader": ["Content-Type", "Cache-Control"]
}]
"Cache-Control" needs to be listed in the "responseHeader" field. Then upload like you normally would, but set the Cache-Control
header. Using fetch
it would be:
fetch(uploadUrl, {
method: 'PUT',
body: blob,
headers: {
'Content-Type': blob.type,
'Cache-Control': 'public, max-age=31536000',
},
});
Upvotes: 3
Reputation: 342
the snippet you have is getting a signed url. when you upload (insert) the object into GCS, you should be able to set it via the API:
https://cloud.google.com/storage/docs/json_api/v1/objects/insert
Upvotes: -1