如何将内存中的multer文件缓冲区上传到google云存储桶?

时间:2018-03-27 05:19:44

标签: node.js firebase google-cloud-storage multer

我正在使用带有nodejs的multer来处理多部分表单数据。我不想保存从客户端获取的req.file。我想直接将内存中的文件缓冲区上传到谷歌云存储......

但是存储桶(firebase存储)上传方法只接受文件路径作为参数。有没有什么方法可以直接实现这个而不保存文件并将内存中的文件缓冲区直接上传到firebase存储?

如果是这样,怎么办?

2 个答案:

答案 0 :(得分:0)

The documentation lists options for uploading

您可以使用File.createWriteStream()创建可用于从内存上传数据的WritableStream。 API文档显示了此示例:

var fs = require('fs');
var storage = require('@google-cloud/storage')();
var myBucket = storage.bucket('my-bucket');

var file = myBucket.file('my-file');

//-
// <h4>Uploading a File</h4>
//
// Now, consider a case where we want to upload a file to your bucket. You
// have the option of using {@link Bucket#upload}, but that is just
// a convenience method which will do the following.
//-
fs.createReadStream('/Users/stephen/Photos/birthday-at-the-zoo/panda.jpg')
  .pipe(file.createWriteStream())
  .on('error', function(err) {})
  .on('finish', function() {
    // The file upload is complete.
  });

//-
// <h4>Uploading a File with gzip compression</h4>
//-
fs.createReadStream('/Users/stephen/site/index.html')
  .pipe(file.createWriteStream({ gzip: true }))
  .on('error', function(err) {})
  .on('finish', function() {
    // The file upload is complete.
  });

//-
// Downloading the file with `createReadStream` will automatically decode the
// file.
//-

//-
// <h4>Uploading a File with Metadata</h4>
//
// One last case you may run into is when you want to upload a file to your
// bucket and set its metadata at the same time. Like above, you can use
// {@link Bucket#upload} to do this, which is just a wrapper around
// the following.
//-
fs.createReadStream('/Users/stephen/Photos/birthday-at-the-zoo/panda.jpg')
  .pipe(file.createWriteStream({
    metadata: {
      contentType: 'image/jpeg',
      metadata: {
        custom: 'metadata'
      }
    }
  }))
  .on('error', function(err) {})
  .on('finish', function() {
    // The file upload is complete.
  });

答案 1 :(得分:0)

该解决方案就在nodejs的云存储入门指南中。

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

参考:https://cloud.google.com/nodejs/getting-started/using-cloud-storage