gpt4 book ai didi

node.js - 重新组装分段上传中生成的文件 block

转载 作者:太空宇宙 更新时间:2023-11-03 22:17:11 24 4
gpt4 key购买 nike

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

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

上传工作正常,但我无法将这些部分重新组合成一个二进制文件。我从库作者在 Github ( https://github.com/flowjs/flow.js/tree/master/samples/Node.js ) 上提供的 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 目录(这是我保存 block 的位置)中生成重新组装的二进制文件。然而什么也没有发生。我错过了什么?

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

最佳答案

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

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

就是这样!

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

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

    r.write(identifier, stream);

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

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

关于node.js - 重新组装分段上传中生成的文件 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23093146/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com