Given an image url, how can I upload that image to Google Cloud Storage for image processing using Node.js?
To add onto Yevgen Safronov's answer, we can pipe the request into the write stream without explicitly downloading the image into the local file system.
const request = require('request');
const storage = require('@google-cloud/storage')();
function saveToStorage(attachmentUrl, bucketName, objectName) {
const req = request(attachmentUrl);
req.pause();
req.on('response', res => {
// Don't set up the pipe to the write stream unless the status is ok.
// See https://stackoverflow.com/a/26163128/2669960 for details.
if (res.statusCode !== 200) {
return;
}
const writeStream = storage.bucket(bucketName).file(objectName)
.createWriteStream({
// Tweak the config options as desired.
gzip: true,
public: true,
metadata: {
contentType: res.headers['content-type']
}
});
req.pipe(writeStream)
.on('finish', () => console.log('saved'))
.on('error', err => {
writeStream.end();
console.error(err);
});
// Resume only when the pipe is set up.
req.resume();
});
req.on('error', err => console.error(err));
}