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

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

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

提交回复
热议问题