formidable实现node.js中的文件上传

效果图

formidable实现node.js中的文件上传_node.js

formidable实现node.js中的文件上传_文件上传_02

核心代码

var express = require("express");
var formidable = require('formidable');
var util = require("util");
var app = express();

app.engine('htm', require('express-art-template')) //设置模板引擎

app.get("/", function(req, res) {

res.render('index.htm');
})

app.post('/dopost', function(req, res) {

var form = new formidable.IncomingForm(); //获取formidable对象
form.uploadDir = "./uploads"; //指定上传文件夹(必须提前手动创建)
form.keepExtensions = true; //保持拓展名不变
form.parse(req, function(err, fields, files) {

res.send('ok');

});
})

app.listen(3000, function() {
console.log("run server____");
})

html代码

<!DOCTYPE html>
<html lang="zh-CN">

<head>
<meta charset="UTF-8">
<title>文件上传</title>
</head>

<body>

<form action="/dopost" method="POST" enctype="multipart/form-data">
<p><input type="file" name="file"></p>
<p><input type="submit" value="确定上传"></p>
</form>
</body>

</html>

package.json文件

{
"name": "elective-course-registeration-stytem",
"version": "1.0.0",
"description": "冷月心最喜欢的后台语言,node.js",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "冷月心",
"license": "ISC",
"dependencies": {
"ejs": "^2.5.6",
"express": "^4.15.2",
"express-session": "^1.15.2",
"formidable": "^1.1.1",
"mongoose": "^4.9.2",
"node-xlsx": "^0.7.4",
"underscore": "^1.8.3",
"art-template": "^4.12.2",
"bootstrap": "^3.3.7",
"express-art-template": "^1.0.0"
}
}

项目初始化

进入项目文件夹 npm i ,自动安装package.json文件所有依赖