Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/40.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 连接总线男孩捕获无文件场景_Node.js_Express_Busboy - Fatal编程技术网

Node.js 连接总线男孩捕获无文件场景

Node.js 连接总线男孩捕获无文件场景,node.js,express,busboy,Node.js,Express,Busboy,我正在使用connect-busboy上传一个文件作为电子邮件附件。如果存在一个文件,代码工作正常。但是,我想捕捉没有附加/上传文件的场景 起初我以为我会检查文件的大小是否为零,但后来我意识到busboy.on('file')本身并没有被触发 如何检查是否未上载任何文件并继续下一步 代码如下: if (req.busboy) { req.busboy.on('field', function (fieldname, value) { console.log('Field

我正在使用
connect-busboy
上传一个文件作为电子邮件附件。如果存在一个文件,代码工作正常。但是,我想捕捉没有附加/上传文件的场景

起初我以为我会检查文件的大小是否为零,但后来我意识到busboy.on('file')本身并没有被触发

如何检查是否未上载任何文件并继续下一步

代码如下:

if (req.busboy) {
    req.busboy.on('field', function (fieldname, value) {
        console.log('Field [' + fieldname + ']: value: ' + value);
        // collecting email sending details here in field
    });

    var now = (new Date).getTime();
    req.busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
        var attachmentfile = '/tmp/' + now + '.' + filename;
        fstream = fs.createWriteStream(attachmentfile);
        file.pipe(fstream);
        fstream.on('close', function () {
            console.log("Upload Finished of " + filename);
            console.log('Time to upload: ' + utility.getFormattedTime((new Date).getTime() - now));
            attachment.file = { 'name': filename, 'location': attachmentfile };

            // send email code

            return res.send('email sent successfully');
        });
    });

    req.busboy.on('finish', function () {
        // validating if input from reading field values are correct or not
    });
} else {
    res.error('No file attached');
}
我用于无文件测试的curl命令是:

curl -X POST \
    http://localhost:3000/email/ \
    -H 'Cache-Control: no-cache' \
    -H 'content-type: multipart/form-data;' \
    -F 'data={'some json object' : 'json value'}'
如果我在上面的curl命令中添加
-F'file=@location'
,代码工作正常


我缺少什么?

如果有文件,可以使用设置为true的变量

if (req.busboy) {

    var fileUploaded = false;

    req.busboy.on('field', function (fieldname, value) {
        ...
    });

    var now = (new Date).getTime();
    req.busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {

        fileUploaded = true;
        ...
    });

    req.busboy.on('finish', function () {

        if (!fileUploaded) {

            res.error('No file attached');

        } else {

            // ----- a file has been uploaded
        }

    });
} else {
    res.error('No file attached');
}