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

后端 未结 6 769
南旧
南旧 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:57

    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)
    

提交回复
热议问题