Express框架入门(三)结合 multer 上传图片
一、 Multer 模块介绍二、 Express 上传文件模块 multer 的使用1. 安装 multer2. 引入配置 multer 模块3.使用 multer三、 Express 按照日期生成上传文件目录四、 多文件上传五、综合案例一、 Multer 模块介绍
Multer 是一个 node.js 中间件,用于处理 multipart/form-data 类型的表单数据,它主要用于上传文件。它是写在 busboy 之上非常高效。
注意: Multer 不会处理任何非 multipart/form-data 类型的表单数据。
二、 Express 上传文件模块 multer 的使用
1. 安装 multer
npm install --save multer
2. 引入配置 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 })
3.使用 multer
router.post('/doAdd', upload.single("pic"), function (req, res) {res.send({file: req.file,//返回文件名 body: req.body }) });
三、 Express 按照日期生成上传文件目录
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) {})
五、综合案例
app.js
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>
在上面的基础上进行封装
新增model下的tools.js
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、获取当前日期 2003let day=sd.format(new Date(), 'YYYYMMDD');// static/upload/2003let 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、获取当前日期 2003let day=sd.format(new Date(), 'YYYYMMDD');// static/upload/2003let 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>