Reputation: 41
After searching on Google, i find that there is no function into npm GCS client yet. i found that i will achieve it by running one instance which will have one image download service & it will download image at there for temp purpose & upload it to GCS bucket. in this situation , do i have to pay extra four charges like running instance ,downloading image(temp) bandwidth & also image transfer/storing into GCS bucket. ?
Also find one solutions https://cloudinary.com/documentation/fetch_remote_images cloudinary is exactly what i am looking it.
i am curious to know that is it possible to achieve same kind of thing using GCS bucket. if yes then please tell how ?
I am looking for ideal way.
Upvotes: 2
Views: 2642
Reputation: 4441
Assuming you want to use using Google Cloud Client Libraries, I uploaded an image from an external URL, using Node.JS v8.9.4 and npm version 5.6.0 to my bucket, using this code:
const {Storage} = require('@google-cloud/storage'),
request = require('request'),
bucket = 'BUCKET_NAME',
filename = 'FILE_NAME',
url = 'IMAGE_URL',
storage = new Storage({
projectId: 'PROJECT_ID',
keyFilename: 'auth.json'
});
var file = storage.bucket(bucket).file(filename);
request({url: url, encoding: null}, function(err, response, buffer) {
var stream = file.createWriteStream({
metadata: {
contentType: response.headers['content-type']
}
});
stream.end(buffer);
});
Make sure you set PROJECT_ID
, BUCKET_NAME
, FILE_NAME
and IMAGE_URL
; as well as having the Service Account JSON key file in the local directory.
Contents of package.json:
{
"dependencies": {
"@google-cloud/storage": "^2.3.3"
}
}
Run the code with npm start server.js
.
If you wish to get a Signed URL for this file, add the following extra code I found in the documentation:
// These options will allow temporary read access to the file
const options = {
action: 'read',
expires: '03-17-2025',
};
storage
.bucket(bucket)
.file(filename)
.getSignedUrl(options)
.then(results => {
const signed_url = results[0];
console.log(`The signed URL for ${filename} is ${signed_url}`);
})
.catch(err => {
console.error('ERROR:', err);
});
Don't forget to set the expiry date to the actual date of expiry you're interested in, by modifying the value of expires
.
Upvotes: 1