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

后端 未结 6 778
南旧
南旧 2021-02-03 11:33

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

6条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-03 11:49

    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

提交回复
热议问题