我正在使用busboy模块上传文件。它适用于一个文件。但是,当我尝试上传多个文件时,它会抛出以下错误。
Error: Can't set headers after they are sent
我知道为什么抛出错误,但我无法弄清楚解决方案。以下是我的代码段。
exports.uploadFile = function (req, res) {
console.log('Calling uploadFile inside FileUploadService');
var fstream;
req.pipe(req.busboy);
req.busboy.on('file', function (fieldName, file, fileName) {
// Get folderGuid
var folderGuid = req.params.folderGuid;
//Get folderName
var folderName = req.query.folderName;
//path of file contents
var directoryPath = fileRepositoryPath + "/" + folderGuid+"/"+folderName;
//Get location
var filePath = directoryPath + "/" + fileName;
log.debug("inside FileUploadService ::: uploadFile >> folderGuid: " + folderGuid + ", directoryPath : " + directoryPath + ", filePath : " + filePath);
//Create directory
nodefs.mkdir(directoryPath, 0777, true, function (err) {
if (err) {
log.error({err: err}, 'Error while creating recurrisve directory');
} else {
log.debug('inside FileUploadService ::: uploadFile >> Directory created');
}
//Write object on file system
fstream = nodefs.createWriteStream(filePath);
file.pipe(fstream);
fstream.on('close', function (err) {
if (!err) {
var relativePath = "/" + folderGuid + "/" + fileName;
log.info('Successfully uploaded file relativePath >> '+relativePath);
res.status(constants.HTTP_CODE_OK);
res.json({"relativePath": relativePath});
} else {
log.error({err: err}, 'Failed to upload file');
res.status(constants.HTTP_CODE_INTERNAL_SERVER_ERROR);
res.json({error: err});
}
});
});
});
};
我知道以下代码行是抛出错误,这是因为在多个文件的情况下,这行代码执行两次会导致错误。
res.status(constants.HTTP_CODE_OK);
res.json({"relativePath": relativePath});
如何跟踪" req.busboy.on('file', function (fieldName, file, fileName)
"的多个事件?所以一旦完成所有文件处理,那么我才应该发送响应吗?
请帮忙。
答案 0 :(得分:1)
Busboy一次处理一个文件,因此根据您的代码响应在一个文件流完成后发送。 现在,当下一个文件流完成时,响应已经发送,因此您收到此错误。
尝试在完成所有文件后发送回复。
req.busboy.on('finish', function() {
res.status(constants.HTTP_CODE_OK);
res.json({"relativePath": relativePath});
});
或尝试在此问题的答案中:busboy-connect fires on finish before the end of save file (node.js , express)
答案 1 :(得分:0)
您可以更改语法,包括“req.pipe(req.busboy);”在“req.busboy.on('file',function(fieldName,file,fileName){})”
之后