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

删除回忆录丶 提交于 2020-07-17 06:45:20

问题


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


回答1:


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




回答2:


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



回答3:


Incase of handling image uploads from a remote url. In reference to the latest library provided by Google docs. Instead of storing the buffer of image. We can directly send it to storage.

function sendUploadUrlToGCS(req, res, next) {
  if (!req.body.url) {
    return next();
  }

  var gcsname = Date.now() + '_name.jpg';
  var file = bucket.file(gcsname);

  return request({url: <remote-image-url>, encoding: null}, function(err, response, buffer) {
    req.file = {};
    var stream = file.createWriteStream({
      metadata: {
        contentType: response.headers['content-type']
      }
    });

    stream.on('error', function(err) {
       req.file.cloudStorageError = err;
       console.log(err);
       next(err);
    });

    stream.on('finish', function() {
      req.file.cloudStorageObject = gcsname;
      req.file.cloudStoragePublicUrl = getPublicUrl(gcsname);
      next();
    });

    stream.end(buffer);
  });
}



回答4:


utility.js

 // google cloud stoage 
 let fs                = require('fs');
 const { Storage }     = require('@google-cloud/storage');
 var credentials       = require('../../yourProjectCredentials.json');
 const storage         = new Storage({credentials: credentials});

 const bucketName      = 'pictures';

 const uuidV1          = require('uuid/v1');
 var dir               = './images';



/**
 * Store Image to GCP Buket
 * @param { picture }
 * @returns { picture_url }
 */
class ApplicationUtility{

    constructor(){}

    /**
     * Store Image to GCP Buket
     * @param { picture }
     * @returns { picture_url }
     */

    async storeImageTocloud (picture) {

        let fileNamePic = uuidV1();
        let path2 = fileNamePic + "_picture.jpg";
        let path = dir + "/" + path2;
        var bitmap = new Buffer.from(picture, 'base64');
        fs.writeFileSync(path, bitmap, { flag: 'w' }, (err) => {
            if (err)
                throw (err);
        });
        storage
            .bucket(bucketName)
            .upload(path)
            .then(() => console.log(`${fileNamePic} uploaded to 
             ${bucketName}.`))
            .catch(err => { throw (err) });

        let url = `https://storage.googleapis.com/${bucketName}/${path2}`;
        return url;

    }

}


module.exports = ApplicationUtility;

index.js

  const ImagesStorage              = require('./utility');
  const imagesStorage              = new ImagesStorage();

        //call 
        let picture = body.pic
        let url = await imagesStorage.storeImageTocloud(picture);
        console.log(url)


来源:https://stackoverflow.com/questions/36661795/how-to-upload-an-image-to-google-cloud-storage-from-an-image-url-in-node

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!