需要在Node.js中验证文件输入

时间:2014-11-06 13:02:50

标签: node.js mongodb file-upload express mongoose

我使用Node + Express + MongoDB来开发我的应用程序。在我的应用程序中有许多文件上载表单。完成上传过程。但我的问题是,目前没有验证文件输入。我需要验证这些文件输入,比如

  
      
  1. 只需上传.jpeg,.png文件。

  2.   
  3. 文件大小必须小于1MB。

  4.   

但不知道如何解决这个问题。我使用mongoose.js'模型模式来验证字符串和数字。搜索了很多寻找文件验证的解决方案,但失败了。任何知道如何处理这个问题的人,请帮帮我

1 个答案:

答案 0 :(得分:0)

您应该使用npm模块'mmmagic'来检查文件类型

  var mmm = require('mmmagic'),
  Magic = mmm.Magic;

  var magic = new Magic(mmm.MAGIC_MIME_TYPE | mmm.MAGIC_MIME_ENCODING);
  // the above flags can also be shortened down to just: mmm.MAGIC_MIME_TYPE
  magic.detectFile('path/to/your/file.jpg', function(err, result) {
     if (err) throw err;
     console.log(result);//result is an object containig the file type
  });

您可以使用'fs'节点模块检查文件大小