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

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

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

提交回复
热议问题