重新组装分段上传中生成的文件块

2024-01-29

我正在使用优秀的 flow.js 库来处理文件上传。这是一个可恢复的 HTML5 上传,会在服务器上生成一堆必须重新组装的块。例如,foo.mov 可能会变成

timestamp-foomov.1
timestamp-foomov.2
...
timestamp-foomov.n

上传正常,但我在将各个部分重新组合成单​​个二进制文件时遇到问题。我从库作者在 Github 上提供的 Node.js 服务器示例中获得了以下代码(https://github.com/flowjs/flow.js/tree/master/samples/Node.js https://github.com/flowjs/flow.js/tree/master/samples/Node.js).

  $.write = function(identifier, writableStream, options) {
  options = options || {};
  options.end = (typeof options['end'] == 'undefined' ? true : options['end']);

  // Iterate over each chunk
  var pipeChunk = function(number) {

      var chunkFilename = getChunkFilename(number, identifier);
      fs.exists(chunkFilename, function(exists) {

          if (exists) {
              // If the chunk with the current number exists,
              // then create a ReadStream from the file
              // and pipe it to the specified writableStream.
              var sourceStream = fs.createReadStream(chunkFilename);
              sourceStream.pipe(writableStream, {
                  end: false
              });
              sourceStream.on('end', function() {
                  // When the chunk is fully streamed,
                  // jump to the next one
                  pipeChunk(number + 1);
              });
          } else {
              // When all the chunks have been piped, end the stream
              if (options.end) writableStream.end();
              if (options.onDone) options.onDone();
          }
      });
  }
  pipeChunk(1);
  }

我使用以下路径调用此代码,并期望它在 tmp 目录(这是我保存块的位置)中生成重新组装的二进制文件。然而什么也没有发生。我缺少什么?

exports.download = function(req, res, next) {
switch(req.method) {
    case 'GET':
    var stream = fs.createWriteStream('foobar');
    flow.write(req.params.identifier, res);
    break;
}
}

重新组装所有块很容易,只需调用:

     var stream = fs.createWriteStream(filename);
     r.write(identifier, stream);

就是这样!

但另一个问题是,什么时候应该调用这个方法? 也许当所有块都上传并出现在 tmp 文件夹中时。

但是重复调用 done 还存在另一个问题。 一旦所有块都存在,就可以通过创建并锁定文件来解决这个问题。 然后打电话

    r.write(identifier, stream);

然后清理所有块,释放锁并关闭文件。

在 php 服务器端库中也采用了相同的方法:https://github.com/flowjs/flow-php-server/blob/master/src/Flow/File.php#L102 https://github.com/flowjs/flow-php-server/blob/master/src/Flow/File.php#L102

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

重新组装分段上传中生成的文件块 的相关文章

随机推荐