Given an image url, how can I upload that image to Google Cloud Storage for image processing using Node.js?
I used the request library and storage library for make it. The code below is in TypeScript. Regards
import * as gcs from '@google-cloud/storage';
import {Storage} from '@google-cloud/storage';
import request from 'request';
private _storage: Storage;
constructor() {
// example of json path: ../../config/google-cloud/google-storage.json
this._storage = new gcs.Storage({keyFilename: 'JSON Config Path'});
}
public saveFileFromUrl(path: string): Promise {
return new Promise((resolve, reject) => {
request({url: path, encoding: null}, (err, res, buffer) => {
if (res.statusCode !== 200) {
reject(err);
}
const bucketName = 'bucket_name';
const destination = `bucket location and file name`; // example: 'test/image.jpg'
const file = this._storage.bucket(bucketName).file(destination);
// put the image public
file.save(buffer, {public: true, gzip: true}).then(data => {
resolve(`${bucketName}/${destination}`)
}).catch(err => {
reject(err);
});
});
})
}