gpt4 book ai didi

javascript - busboy-connect 在保存文件结束前触发(node.js,express)

转载 作者:行者123 更新时间:2023-11-30 07:59:26 25 4
gpt4 key购买 nike

我使用 busboy connect 从我的客户端获取上传数据。我尝试保存数据,然后 on.finish 将状态 ok 返回给服务器。问题是 on.finish 在文件保存结束之前触发。是我做错了什么还是模块就是这样工作的?

服务器端代码:

        console.log("upload started dirname ", __dirname);
var fstream;
var result = [];
var number_of_files = 1;
req.pipe(req.busboy);
req.busboy.on('field', function(fieldname, val) {
field_obj = {}
field_obj[fieldname] = val;
result.push(field_obj);
console.log(field_obj)
});
req.busboy.on('file', function(fieldname, file, filename) {
console.log("Uploading: " + filename);
//Path where image will be uploaded
if (result.length > 0) {
var file_type = filename.substr(filename.length - 4);
filename = result[0].name + '_' + number_of_files + file_type;
number_of_files++;
}
fstream = fs.createWriteStream(__dirname + "/" + filename);
file.pipe(fstream);
fstream.on('close', function() {
console.log("Upload Finished of " + filename);
result.push(filename);
console.log("result ",result)
});
});
req.busboy.on('finish', function() {
console.log("form parsing finished")
console.log("result finish",result)
res.sendStatus(200)
});

我希望“结果完成”是我看到的最后一条消息,但我在我的控制台上得到以下信息:

Uploading: testSwf1.swf
Uploading: testSwf3.swf
form parsing finished
result finish [ { name: '123' }, { clickUrl: '234234' } ]
Upload Finished of 123_1.swf
result [ { name: '123' }, { clickUrl: '234234' }, '123_1.swf' ]
Upload Finished of 123_2.swf
result [ { name: '123' },
{ clickUrl: '234234' },
'123_1.swf',
'123_2.swf' ]

编辑我也尝试了 on.end 但那个根本没有开火。

req.busboy.on('end', function() {
console.log("DONE PARSING FORM")
console.log("NEW result finish", result)
});

最佳答案

这是预期的行为。 finish 在从请求中读取最后一个数据时发出(这包括任何/所有发出的 file 流,它们是传入请求数据的子集)。

但是,如果您正在将 file 流写入磁盘,则 file 流可能仍有最后一 block 数据仍在内存中缓冲.这就是为什么在发出 finish 时文件可能没有完全写入磁盘的原因。

一个常见的解决方案是检查在 busboy finish 事件处理程序中设置的标志,并检查每次 fstream close 时递增的计数器变量事件(例如将其与 result.length 进行比较)。

关于javascript - busboy-connect 在保存文件结束前触发(node.js,express),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32009583/

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