如何使用强大的节点js获取文件扩展名?
How to get file extension in node js using formidable?
我的代码:
Js 文件:
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; }
});
});
});
Html/Ejs 文件:
<html>
<title> <%= title %> </title>
<body>
<h2> Form </h2>
<form action="/form" method="post" enctype="multipart/form-data">
Name: <input type="text" name="name" /><br>
File: <input type="file" name="fil" />
<input type="submit" value="Submit">
</form>
</body>
</html>
所有软件包均已正确安装,使用此代码,文件(具有任何扩展名)已正确上传到所需目录。
我想要的是只上传图像文件,例如:- jpeg、png 等
谢谢。
使用此代码:
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
我的代码:
Js 文件:
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; }
});
});
});
Html/Ejs 文件:
<html>
<title> <%= title %> </title>
<body>
<h2> Form </h2>
<form action="/form" method="post" enctype="multipart/form-data">
Name: <input type="text" name="name" /><br>
File: <input type="file" name="fil" />
<input type="submit" value="Submit">
</form>
</body>
</html>
所有软件包均已正确安装,使用此代码,文件(具有任何扩展名)已正确上传到所需目录。
我想要的是只上传图像文件,例如:- jpeg、png 等
谢谢。
使用此代码:
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