ejs前端代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="1.css">
</head>
<body>
<ul>
<% for( let i=0; i< host.length;i++){%>
<li>
<%=host[i].username%>
<!-- <img src="1.jpeg" /> -->
<img src="<%=host[i].image%>" alt="">
</li>
<%}%>
</ul>
<form action="/add" method="post" enctype="multipart/form-data">
请输入用户名: <input type="text" name="title" id="title" /><br>
<input type="file" name="file">
<button type=" submit ">发送</button>
</form>
</body>
</html>
后端实现具体逻辑实现:
const express = require('express')
const ejs = require('ejs')
const app = express()
//绑定请求体参数
const bodyParser = require('body-parser')
const multer = require('multer')
//日期插件
const dayjs = require('dayjs')
const path = require('path')
//自动生成文件的插件(异步操作)
const mkdirp = require('mkdirp')
const storage = multer.diskStorage({
destination: async function(req, file, cb) {
//生成当前日期
let day = dayjs().format('YYYYMMDD')
console.log(day);
//跟据日期生成文件夹
let dir = path.join('public', day)
//将异步操做使用 await
await mkdirp(dir)
//存放的路径
cb(null, dir)
},
filename: function(req, file, cb) {
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
//显示的文件后缀名
let excename = path.extname(file.originalname)
// console.log(excename);
cb(null, file.fieldname + uniqueSuffix + excename)
}
})
//添加图片
const upload = multer({ storage: storage })
app.use(express.json())
app.use(bodyParser.urlencoded())
//配置模板文件
//使用ejs渲染页面
app.engine('html', ejs.__express)
app.set('view engine', 'html')
//配置静态文件
app.use(express.static('public'))
//初定义用户
let host = [{
username: "zs",
image: '1.jpeg'
},
{
username: "ls",
image: '1.jpeg'
},
]
app.get('/', (req, res, next) => {
res.render('index', { host })
})
app.post('/add', upload.single('file'), (req, res, next) => {
//对文件路径进行拼接
let url = req.file.path.split('\\')
let url1 = path.join(url[1], url[2])
//将新添加的用户传渲染到页面
host.push({
username: req.body.title,
image: url1
})
//然后重定向
res.redirect('/')
})
const port = 3000
//测试
app.get('/', (req, res) => res.send('Hello World!'))
//监听端口
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
功能具体:
点击输入用户名,和用户头像,及时渲染到页面(ui有点丑,主要是功能!)