How to upload an image to Google Cloud Storage from an image url in Node?

Harris Lummis picture Harris Lummis · Apr 16, 2016 · Viewed 12.5k times · Source

Given an image url, how can I upload that image to Google Cloud Storage for image processing using Node.js?

Answer

Yevgen Safronov picture Yevgen Safronov · Apr 16, 2016

It's a 2 steps process:

  • Download file locally using request or fetch.
  • Upload to GCL with the official library.

    var fs = require('fs');
    var gcloud = require('gcloud');
    
    // Authenticating on a per-API-basis. You don't need to do this if you auth on a
    // global basis (see Authentication section above).
    
    var gcs = gcloud.storage({
      projectId: 'my-project',
      keyFilename: '/path/to/keyfile.json'
    });
    
    // Create a new bucket.
    gcs.createBucket('my-new-bucket', function(err, bucket) {
      if (!err) {
        // "my-new-bucket" was successfully created.
      }
    });
    
    // Reference an existing bucket.
    var bucket = gcs.bucket('my-existing-bucket');                
    var localReadStream = fs.createReadStream('/photos/zoo/zebra.jpg');
    var remoteWriteStream = bucket.file('zebra.jpg').createWriteStream();
    localReadStream.pipe(remoteWriteStream)
      .on('error', function(err) {})
      .on('finish', function() {
        // The file upload is complete.
      });
    

If you would like to save the file as a jpeg image, you will need to edit the remoteWriteStream stream and add custom metadata:

var image = bucket.file('zebra.jpg');
localReadStream.pipe(image.createWriteStream({
    metadata: {
      contentType: 'image/jpeg',
      metadata: {
        custom: 'metadata'
      }
    }
}))

I found this while digging through this documentation