如何使用formidable在节点js中获取文件扩展名?

时间:2017-08-06 16:40:58

标签: javascript node.js file upload formidable

我的代码:

Js文件:

UPDATE table t LEFT JOIN
       (SELECT min(id) as minid, option1, option2, option3, option4
        FROM t
        GROUP BY option1, option2, option3, option4
       ) tt
       ON t.id = tt.minid
   SET t.option2 = (CASE WHEN tt.minid IS NOT NULL THEN LOWEST ELSE  NOT_LOWEST END)
   WHERE option1 = 'a';

Html / Ejs文件:

var formidable = require('formidable');  
var fs = require('fs');  
var ex = require('express');  
var fse = require('fs-extra');  
var app = ex();

app.set('view engine', 'ejs');

app.get('/form', function(req, res) {  
  res.render(__dirname + '/views/front.ejs', {title: 'form-page'});  
}).listen(8081);

app.post('/form', function(req, res) {
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
      var oldpath = files.fil.path;
      var newpath = __dirname + '/uploads/' + files.fil.name;
      var fileExt = files.fil.name.split('.').pop();
      fse.move (oldpath, newpath, function (err) {
         if (err) { throw err; }
      });
   });
});  

所有软件包都已正确安装,使用此代码,文件(具有任何扩展名)将正确上载到所需目录。

我想要的只是上传图像文件: - jpeg,png等 谢谢。

1 个答案:

答案 0 :(得分:1)

使用此代码:

form.onPart = function (part) {
    if(!part.filename || part.filename.match(/\.(jpg|jpeg|png)$/i)) {
        this.handlePart(part);
    }
    else {
        console.log(part.filename + ' is not allowed');
    }
}

来源:uploading files using express.js and node, limiting extensions