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

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

    I used the request library and storage library for make it. The code below is in TypeScript. Regards

    import * as gcs from '@google-cloud/storage';
    import {Storage} from '@google-cloud/storage';
    import request from 'request';
    
    private _storage: Storage;
    
    constructor() {
        // example of json path: ../../config/google-cloud/google-storage.json
        this._storage = new gcs.Storage({keyFilename: 'JSON Config Path'});
    }
    
    public saveFileFromUrl(path: string): Promise {
        return new Promise((resolve, reject) => {
            request({url: path, encoding: null}, (err, res, buffer) => {
                if (res.statusCode !== 200) {
                    reject(err);
                }
                const bucketName = 'bucket_name';
                const destination = `bucket location and file name`; // example: 'test/image.jpg'
                const file = this._storage.bucket(bucketName).file(destination);
                // put the image public
                file.save(buffer, {public: true, gzip: true}).then(data => {
                    resolve(`${bucketName}/${destination}`)
                }).catch(err => {
                    reject(err);
                });
            });
        })
    }
    

提交回复
热议问题