文件长度和文件数据之前发送回响应?我正在上传单个文件"/>
Busboy在读取文件长度和文件数据之前发送回响应?我正在上传单个文件
module.exports.upload = function (req, res) {
fileName = path.basename(req.query.fileName);
var fileExtn = path.extname(req.query.fileName);
console.log("fileName " + fileName);
console.log("fileExtn " + fileExtn);
var fileCheckResponse = FileCheck(req, res); // FileCheck method containing Busboy code
console.log("file check response =" + fileCheckResponse);
}
function FileCheck(req, res) {
var dataSize;
var busboy = new Busboy({ headers: req.headers });
busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
file.on("data", function (data) {
dataSize=data.length;
console.log("File [" + fieldname + "] got " + data.length + " bytes");
console.log("the upload file data ===== " + data);
})
});
busboy.on('finish', function() {
console.log('Upload complete');
return dataSize;
});
return req.pipe(busboy);
}`
这里是从上传方法中,我调用存在Busboy代码的FileCheck函数,然后我首先打开调试并检入FileCheck函数,然后它就命中了(busboy.on('file',function(fieldname,file,filename,filename,encoding,mimetype )),那么它就不会进入另一行(busboy.on('finish',function()),然后响应对象返回到上载方法,我希望在fileCheckResponse中使用datalenght,但是会得到不包含它的对象,再次在继续调试时再次返回FileCheck函数,这一次命中(file.on(“ data”,function(data))并在控制台上打印数据,正如我所写的,但响应没有返回到上载方法。
再次,我的问题和目标是获取数据长度作为响应,但是现在我第一次获取对象作为响应,而第二次指针没有回到上传方法。
回答如下:// try using const or let instead of var
module.exports.upload = function (req, res) {
fileName = path.basename(req.query.fileName);
const fileExtn = path.extname(req.query.fileName)
console.log("fileName " + fileName);
console.log("fileExtn " + fileExtn);
// try to make FileCheck function synchronous using promise or async await
FileCheck(req, res)
.then(fileSize => {
console.log(fileSize, 'fileSize')
// send whatever response you need
})
}
function FileCheck(req, res) {
return new Promise((resolve, reject) => {
let dataSize;
let busboy = new Busboy({ headers: req.headers });
busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
file.on('data', function (data) {
dataSize = data.length;
console.log("File [" + fieldname + "] got " + data.length + " bytes");
})
});
busboy.on('finish', function() {
console.log('Upload complete');
resolve(dataSize)
});
req.pipe(busboy)
})
}
更多推荐
Busboy在读取文件长度和文件数据之前发送回响应?我正在上传单个文件
发布评论