Harris Lummis Harris Lummis - 6 months ago 142
Node.js Question

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

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

Answer

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);
    

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