Node.js学习——Express使用multer上传文件

代码地址:https://github.com/wxyzcctv/OperateExpressMulter

代码结构

app.js

const express = require('express')
const ejs = require('ejs');
const bodyParser = require('body-parser');
const app = express()
const port = 3000;
// 引入路由模块
const login = require('./routers/login');
const api = require("./routers/api")
const index = require("./routers/index")
const admin = require("./routers/admin")

//配置模板引擎
app.engine("html", ejs.__express)
app.set("view engine", "html")
//配置静态web目录
app.use(express.static("static"))
//配置第三方中间件,此处配置的bodyParser是全局的配置,在下面的login中间件中是可以直接使用的
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

// 当访问/login路由时直接使用login路由模块
app.use('/login', login);
app.use('/admin', admin);
app.use('/api', api);
app.use('/', index);

app.listen(port, () => console.log(`Example app listening on port ${port}!`))

封装multer方法

moduls/tools.js

const multer  = require('multer');
const mkdirp = require('mkdirp');
const sd = require('silly-datetime');
const path = require('path');

let tools = {
    multer: () => {
        const storage = multer.diskStorage({
            //配置上传的目录
            destination: async (req, file, cb) => {
                // 生成格式化日期
                let date = sd.format(new Date(), 'YYYYMMDD');
                // 获取目录路径
                let dir = path.join('static/uploads', date)
                // 生成目录,异步改同步
                await mkdirp(dir);
                cb(null, dir);
            },
            //修改上传后的文件名
            filename: function (req, file, cb) {
                //1、获取后缀名
                let extname = path.extname(file.originalname);
                //2、根据时间戳生成文件名
                cb(null, Date.now()+extname)
            }
          })
        const upload = multer({ storage: storage });
        return upload;
    },
    
    md5: ()=>{}
}

module.exports = tools;

routers/admin.js

const express = require('express');
const router = express.Router();

const nav = require('./admin/nav');
const center = require('./admin/center')
const user = require('./admin/user');

router.get('/',(req,res)=>{
    res.send('后台管理界面')
})
router.use('/nav',nav);
router.use('/center',center);
router.use('/user',user);

module.exports = router;

使用multer上传单文件

routers/admin/nav.js

const express = require('express');
const router = express.Router();
const tools = require('../../moduls/tools')

router.get('/',(req,res)=>{
    res.send('导航列表')
})

router.get('/add',(req,res)=>{
    res.render('admin/nav/add')
})

router.get('/edite',(req,res)=>{
    res.send('编辑导航')
})

router.post('/doAdd',tools.multer().single('pic'),(req,res)=>{
    res.send({
        files: req.files,
        body: req.body
    })
})

router.post('/doEdite',(req,res)=>{
    res.send('执行编辑')
})

module.exports = router;

views/admin/nav/add.html




    
    
    
    增加导航


    
标题:

图片:

描述:

使用multer上传多个文件

routers/admin/nav.js

const express = require('express');
const tools = require('../../moduls/tools')

var router = express.Router()

router.get("/", (req, res) => {
    res.send("用户列表")
})
router.get("/add", (req, res) => {
    res.render("admin/user/add")
})

const cpUpload = tools.multer().fields([{ name: 'pic1', maxCount: 1 }, { name: 'pic2', maxCount: 1 }])
router.post("/doAdd", cpUpload, (req, res) => {
    res.send({
        files: req.files,
        body: req.body
    })
})

module.exports = router

views/admin/user/add.html




    
    
    
    增加用户


    
标题:

图片1:

图片2:

描述:

你可能感兴趣的:(Node.js学习——Express使用multer上传文件)