【问题标题】:How to upload a list of file to firebase storage from firebase functions如何从firebase函数将文件列表上传到firebase存储
【发布时间】:2017-10-26 08:16:20
【问题描述】:

我有一个 firebase 函数,它将从前端接收带有文件名的请求,该文件将是存储在 firebase 存储中的视频,然后我将应用 ffmpeg 并将视频提取到多个帧中。最后,我会将所有帧上传到 Firebase 存储中。 一切正常,我能够获得所有帧。但是,上传帧存在问题。有时我可以成功上传所有帧,但函数会一直运行直到超时,有时我只能上传第一帧。我是 node.js 的新手。我想 return 或 promise 有问题(我不明白要返回什么以及如何处理 promise)。 另外,我想将每一帧的数据写入数据库。我应该把这部分代码放在哪里?

exports.extractFrame = functions.https.onRequest(function (req, res) {

const name = req.query.fileName;
const username = name.substr(0, name.length - 4);
const sessionId = 'video-org';
const framePath = 'frame-org';

const sourceBucketName = 'this is my bucket name';
const sourceBucket = gcs.bucket(sourceBucketName);
const temDir = os.tmpdir();

return sourceBucket.file(sessionId + '/' + name).download({
    destination: temDir + '/' + name
  }
).then(() => {
  console.log('extract frames');
  return spawn(ffmpegPath, ['-i', temDir + '/' + name, temDir + '/' + 
username + '%d.png']);
}).then(() => {
  const frames = fs.readdirSync(temDir);
  console.log(frames);

for (let index in frames) {
  if (index != 0) {
    console.log('uploading');
    sourceBucket.upload(temDir + '/' + frames[index], {destination: 
framePath + '/' + frames[index]});
  }
}
}).then(() => {
res.send('I am done');
});
});

非常感谢您的帮助!

【问题讨论】:

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


    【解决方案1】:

    将所有对sourceBucket.upload() 的调用中的所有承诺收集到一个数组中,然后使用 Promise.all() 等待整个集合解决后再发送响应:

    const promises = [];
    for (let index in frames) {
      if (index != 0) {
        console.log('uploading');
        const p = sourceBucket.upload(temDir + '/' + frames[index], {destination: 
    framePath + '/' + frames[index]});
        promises.push(p);
      }
    }
    return Promise.all(promises);
    

    此外,您不会从 HTTP 类型函数返回承诺。只需使用res.send() 发送响应即可结束该功能。 documentation中提到了这一点。

    【讨论】:

    • 在这种情况下,我还需要返回下载承诺并生成吗?谢谢
    • 您需要像现在一样链接 Promise,以便让下一步等待上一步,但是从函数返回顶级 Promise 对 HTTP 函数没有任何帮助。
    【解决方案2】:

    不久前我wrote a gist

    // set it up
    firebase.storage().ref().constructor.prototype.putFiles = function(files) { 
      var ref = this;
      return Promise.all(files.map(function(file) {
        return ref.child(file.name).put(file);
      }));
    }
    
    // use it!
    firebase.storage().ref().putFiles(files).then(function(metadatas) {
      // Get an array of file metadata
    }).catch(function(error) {
      // If any task fails, handle this
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-08
      • 2016-11-05
      • 2018-07-12
      • 2018-11-16
      • 2021-03-30
      • 2022-01-12
      • 2020-02-29
      • 2018-06-21
      相关资源
      最近更新 更多