通过nodejs express 4中的单个输入上传多个文件的最佳方法是什么? [英] What is the best way to multiple file upload through a single input in nodejs express 4?

查看:161
本文介绍了通过nodejs express 4中的单个输入上传多个文件的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有express 4的nodejs.我试图通过一个输入字段上传多个文件.我也通过ajax提交表单. 我正在使用express-fileupload中间件来上传文件.当我上传多个文件时,它工作正常.但是,当上传单个文件时,它不起作用. html代码-

I'm using nodejs with express 4. I'm trying to upload multiple file through a single input field. Also I submit my form through ajax. I'm using express-fileupload middleware for uploading files. When i upload multiple files, it works fine. But when upload a single file, it's not working. html code-

<input type="file" name="attach_file" id="msg_file" multiple />

ajax代码-

var data = new FormData();
$.each($('#msg_file')[0].files, function(i, file) {
    data.append('attach_file', file);
});

$.ajax({
    url: '/send_message',
    data: data,
    cache: false,
    contentType: false,
    processData: false,
    method: 'POST',
    type: 'POST',
    success: function(data){
      console.log(data);
    }
});

服务器端js代码-

router.post('/send_message', function(req, res, next){
    if (!req.files)
      res.json('No files were uploaded.');

    let sampleFile = req.files.attach_file;
    console.log(sampleFile.length);

    var file_info = [];
    var count = 0;
    sampleFile.forEach(function(ele, key) {
      ele.mv(path.resolve(`./public/upload/${ele.name}`), function(err) {
        if (err){
          console.log(err);
        }else{
          file_info.push(ele.name);
        }
        count++;
        if(sampleFile.length == count){
          res.json({file_name: file_info });
        }
      });
    });
});

如果我上传单个文件,则console.log(sampleFile.length);显示未定义.

if i upload a single file console.log(sampleFile.length); show undefined.

推荐答案

经过各种测试之后,我发现了问题所在.一切正常,除了我上传单个文件时. 当ajax发送单个文件时,它不是数组.这就是为什么长度没有定义并且forEach没有运行.需要先检查,然后使用mv()函数,如as-

After different kind of testing, I found the issue. Everything is ok except when I upload a single file. When ajax send a single file, it was not an array. That's why, length was undefined and forEach did not run. Need to check first, then use mv() function, like as-

if(sampleFile instanceof Array){
    // here is the forEach block
}else{
    // run a single mv() function
}

这篇关于通过nodejs express 4中的单个输入上传多个文件的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆