首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >连接-busboy不捕获文件场景

连接-busboy不捕获文件场景
EN

Stack Overflow用户
提问于 2018-03-23 19:09:21
回答 1查看 863关注 0票数 1

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

一开始我想我会检查文件的大小为零,但后来我意识到busboy.on(' file ')本身并没有被触发。

如何检查是否没有上载文件并继续下一步?

以下是代码:

代码语言:javascript
复制
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命令是:

代码语言:javascript
复制
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',代码就能正常工作。

我错过了什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-03-23 19:38:18

如果存在文件,则可以使用设置为true的变量。

代码语言:javascript
复制
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');
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49456828

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档