Multer 是一个 node.js 中间件,用于处理 multipart/form-data 类型的表单数据,它主要用于上传文件。它是写在 busboy 之上非常高效。
注意: Multer 不会处理任何非 multipart/form-data 类型的表单数据。
npm install --save multer
var multer = require('multer')
//配置
var storage = multer.diskStorage({
//文件保存路径 注意路径必须存在
destination: function (req, file, cb) {
cb(null, 'public/upload/')
},
//修改文件名称
filename: function (req, file, cb) {
var fileFormat = (file.originalname).split(".");
cb(null,Date.now() + "." + fileFormat[fileFormat.length - 1]);
}
})
var upload = multer({ storage: storage })
router.post('/doAdd', upload.single("pic"), function (req, res) {
res.send({
file: req.file,//返回文件名
body: req.body
})
});
var express = require('express');
var multer = require('multer')
var sd = require('silly-datetime');
var path = require('path');
var mkdirp = require('mkdirp');
var router = express.Router();
//配置
var storage = multer.diskStorage({
//文件保存路径 注意路径必须存在
destination: async (req, file, cb)=> {
// 1、获取当前日期 以及当前的时间戳
let day = sd.format(new Date(), 'YYYYMMDD');
//2、创建图片保存的路径
let dir = path.join('public/upload/',day)
//3、异步创建目录
await mkdirp(dir);
cb(null, dir)
},
//修改文件名称
filename: function (req, file, cb) {
var fileFormat = (file.originalname).split(".");
cb(null,Date.now() + "." + fileFormat[fileFormat.length - 1]);
}
})
var upload = multer({ storage: storage })
router.post('/doAdd', upload.single("pic"), function (req, res) {
res.send({
file: req.file,//返回文件名
body: req.body
})
});
module.exports = router;
var cpUpload = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }])
app.post('/doAdd', cpUpload, function (req, res, next) { })
const express = require("express");
const bodyParser = require('body-parser')
const ejs = require("ejs");
//引入外部模块
const admin = require("./routes/admin")
const index = require("./routes/index")
const api = require("./routes/api")
const app = express()
//配置模板引擎
app.engine("html",ejs.__express)
app.set("view engine","html")
//配置静态web目录
app.use(express.static("static"))
//配置第三方中间件获取post提交的数据
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
//配置外部路由模块
app.use("/admin",admin)
app.use("/api",api)
app.use("/",index)
//监听端口 端口号建议写成3000以上
app.listen(3000)
routes下的admin.js
const express = require("express");
var router = express.Router()
//引入模块
const user = require("./admin/user")
const login = require("./admin/login")
const nav = require("./admin/nav")
router.get("/",(req,res)=>{
res.send("后台管理中心")
})
//挂载路由
router.use("/user",user)
router.use("/login",login)
router.use("/nav",nav)
module.exports = router
routes下的api.js
const express = require("express");
var router = express.Router()
router.get("/",(req,res)=>{
res.send("api接口")
})
module.exports = router
routes下的index.js
const express = require("express");
var router = express.Router()
router.get("/",(req,res)=>{
res.send("首页")
})
module.exports = router
routes下的admin下的login.js
const express = require("express");
var router = express.Router()
router.get("/", (req, res) => {
res.send("用户登录页面")
})
router.get("/doLogin", (req, res) => {
res.send("执行登录")
})
module.exports = router
routes下的admin下的nav.js
const express = require("express");
const multer = require('multer');
const path = require('path')
var storage = multer.diskStorage({
//配置上传的目录
destination: function (req, file, cb) {
cb(null, 'static/upload') //上传之前目录必须存在
},
//修改上传后的文件名
filename: function (req, file, cb) {
//1、获取后缀名
let extname= path.extname(file.originalname);
//2、根据时间戳生成文件名
cb(null, Date.now()+extname)
}
})
var upload = multer({ storage: storage })
var router = express.Router()
router.get("/", (req, res) => {
res.send("导航列表")
})
router.get("/add", (req, res) => {
res.render("admin/nav/add")
})
router.get("/edit", (req, res) => {
res.send("修改导航")
})
router.post("/doAdd", upload.single("pic"), (req, res) => {
//获取表单传过来的数据
res.send({
body: req.body,
file: req.file
});
})
router.post("/doEdit", (req, res) => {
res.send("执行修改")
})
module.exports = router
routes下的admin下的user.js
const express = require("express");
var router = express.Router()
router.get("/", (req, res) => {
res.send("用户列表")
})
router.get("/add", (req, res) => {
res.send("增加用户")
})
router.get("/edit", (req, res) => {
res.send("修改用户")
})
router.post("/doAdd", (req, res) => {
res.send("执行增加")
})
router.post("/doEdit", (req, res) => {
res.send("执行修改")
})
module.exports = router
views下的admin下的nav下的add.html
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>增加导航title>
head>
<body>
<form action="/admin/nav/doAdd" method="post" enctype="multipart/form-data">
标题:<input type="text" name="title" id="title" />
<br>
<br>
图片:<input type="file" name="pic" id="pic" />
<br>
<br>
描述:<textarea name="desc" id="desc" cols="30" rows="10">textarea>
<br>
<br>
<input type="submit" value="提交">
form>
body>
html>
const multer = require('multer');
const path = require('path');
let tools={
multer(){
var storage = multer.diskStorage({
//配置上传的目录
destination: function (req, file, cb) {
cb(null, 'static/upload') //上传之前目录必须存在
},
//修改上传后的文件名
filename: function (req, file, cb) {
//1、获取后缀名
let extname= path.extname(file.originalname);
//2、根据时间戳生成文件名
cb(null, Date.now()+extname)
}
})
var upload = multer({ storage: storage })
return upload;
},
md5(){
}
}
module.exports=tools
routes下的admin下的nav.js
const express = require("express");
const tools = require("../../model/tools");
var router = express.Router();
router.get("/", (req, res) => {
res.send("导航列表")
})
router.get("/add", (req, res) => {
res.render("admin/nav/add")
})
router.get("/edit", (req, res) => {
res.send("修改导航")
})
router.post("/doAdd",tools.multer().single("pic"), (req, res) => {
//获取表单传过来的数据
res.send({
body: req.body,
file: req.file
});
})
router.post("/doEdit", (req, res) => {
res.send("执行修改")
})
module.exports = router
其余的和上面一样
按照日期生成上传文件
tools.js
const multer = require('multer');
const path = require('path');
const sd = require('silly-datetime');
const mkdirp = require('mkdirp')
let tools={
multer(){
var storage = multer.diskStorage({
//配置上传的目录
destination: async (req, file, cb)=>{
//1、获取当前日期 20200703
let day=sd.format(new Date(), 'YYYYMMDD');
// static/upload/20200703
let dir=path.join("static/upload",day)
//2、按照日期生成图片存储目录 mkdirp是一个异步方法
await mkdirp(dir)
cb(null, dir) //上传之前目录必须存在
},
//修改上传后的文件名
filename: (req, file, cb)=> {
//1、获取后缀名
let extname= path.extname(file.originalname);
//2、根据时间戳生成文件名
cb(null, Date.now()+extname)
}
})
var upload = multer({ storage: storage })
return upload;
},
md5(){
}
}
module.exports=tools
其余一样
多文件上传
tools.js
const multer = require('multer');
const path = require('path');
const sd = require('silly-datetime');
const mkdirp = require('mkdirp')
let tools={
multer(){
var storage = multer.diskStorage({
//配置上传的目录
destination: async (req, file, cb)=>{
//1、获取当前日期 20200703
let day=sd.format(new Date(), 'YYYYMMDD');
// static/upload/20200703
let dir=path.join("static/upload",day)
//2、按照日期生成图片存储目录 mkdirp是一个异步方法
await mkdirp(dir)
cb(null, dir) //上传之前目录必须存在
},
//修改上传后的文件名
filename: (req, file, cb)=> {
//1、获取后缀名
let extname= path.extname(file.originalname);
//2、根据时间戳生成文件名
cb(null, Date.now()+extname)
}
})
var upload = multer({ storage: storage })
return upload;
},
md5(){
}
}
module.exports=tools
user.js
const express = require("express");
const tools = require("../../model/tools");
var router = express.Router()
router.get("/", (req, res) => {
res.send("用户列表")
})
router.get("/add", (req, res) => {
res.render("admin/user/add")
})
let cpUpload = tools.multer().fields([{ name: 'pic1', maxCount: 1 }, { name: 'pic2', maxCount: 1 }])
router.post("/doAdd",cpUpload, (req, res) => {
res.send({
body:req.body,
files:req.files
})
})
module.exports = router
views下的admin下的user下的add.html
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>增加导航title>
head>
<body>
<form action="/admin/user/doAdd" method="post" enctype="multipart/form-data">
标题:<input type="text" name="title" id="title" />
<br>
<br>
图片1:<input type="file" name="pic1" id="pic1" />
<br>
<br>
图片2:<input type="file" name="pic2" id="pic2" />
<br>
<br>
描述:<textarea name="desc" id="desc" cols="30" rows="10">textarea>
<br>
<br>
<input type="submit" value="提交">
form>
body>
html>