Uploading a buffer to google cloud storage

懵懂的女人 提交于 2019-12-03 05:48:57

We have an issue about supporting this more easily: https://github.com/GoogleCloudPlatform/gcloud-node/issues/1179

But for now, you can try:

file.createWriteStream()
  .on('error', function(err) {})
  .on('finish', function() {})
  .end(fileContents);

This is actually easy:

  let remotePath = 'some/key/to/store.json';
  let localReadStream = new stream.PassThrough();
  localReadStream.end(JSON.stringify(someObject, null, '   '));

  let remoteWriteStream = bucket.file(remotePath).createWriteStream({ 
     metadata : { 
        contentType : 'application/json' 
     }
  });

  localReadStream.pipe(remoteWriteStream)
  .on('error', err => {
     return callback(err);      
  })
  .on('finish', () => {
     return callback();
  });

The following snippet is from a google example. The example assumes you have used multer, or something similar, and can access the file at req.file. You can stream the file to cloud storage using middleware that resembles the following:

function sendUploadToGCS (req, res, next) {
  if (!req.file) {
    return next();
  }

  const gcsname = Date.now() + req.file.originalname;
  const file = bucket.file(gcsname);

  const stream = file.createWriteStream({
    metadata: {
      contentType: req.file.mimetype
    },
    resumable: false
  });

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

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

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