上传文件 文件处理 服务器渲染
插件:formidable
安装指令:
cnpm i formidable -S
用法:
app.js
const express = require('express');
const fs = require('fs');
const formidable = require('formidable');
const path = require('path');
let app = express();
let router = express.Router();
app.use(router)
// 暴露public下的文件( 访问直接服务器地址加文件地址就可以 如:http://localhost:8888/index.js 就行)
app.use(express.static('./public'))
app.use(express.static('./images'))
app.listen(8888)
app.engine('.html', require('express-art-template'))
app.set('view engine', '.html')
app.set('view options', {
debug: process.env.NODE_ENV !== 'production'
})
let dataList = [
{ name: '赵云', img: '1.jpg' },
{ name: '吕布', img: '2.jpg' },
{ name: '大桥', img: '3.jpg' },
{ name: '曹操', img: '4.jpg' },
{ name: '关羽', img: '5.jpg' }
];
router
.get("/", (req, res) => {
// index.html 是当前文件夹 views 下的 index.html
res.render('index.html', { list: dataList });
})
.post('/add', (req, res, next) => {
// 解析文件用 formidable
let form = new formidable.IncomingForm();
// 配置 指定上传路径
form.uploadDir = path.join(__dirname, '/images');
// 配置 保持原有后缀名
form.keepExtensions = true;
form.parse(req, (err, fields, files) => {
console.log(files);
// console.log(fields);
let name = fields.name;
let fileName = path.parse(files.headImg.path).base;
dataList.push({name, img: fileName});
res.redirect('/');
});
})
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.img{
width: 40px;
}
</style>
</head>
<body>
<ul>
{{ each list }}
<li>
<img src="{{ $value.img }}" class="img">
{{ $value.name }}
</li>
{{ /each }}
</ul>
// 上传文件必须加 enctype="multipart/form-data" 属性
<form action="/add" method="post" enctype="multipart/form-data">
名字:<input type="text" name="name" id="">
头像:<input type="file" name="headImg" id="">
<button>提交</button>
</form>
<script src="index.js"></script>
</body>
</html>
第7集 0分钟