Express combined with multer to achieve file upload function

Time:2021-7-17

Single file upload:

<!--add.ejs-->
<form action="/admin/nav/doAdd" method="post" enctype="multipart/form-data">
    Title: < input type = "text" name = "title" id = "title" > < br > < br >
    Picture: < input type = "file" name = "pic" id = "pic" > < br > < br >
    Description: < textarea name = desc "id = desc" cols = 30 "rows = 10" > < / textarea > < br > < br >
    < input type = submit "value = submit" >
</form>
//NAV. JS file
const express = require('express')
const tools = require('../../model/tools')

router.post('/doAdd', tools.multer().single('pic'), (req, res) => {
    //Get the data from the form
    res.send({
        body: req.body,
        file: req.file
    })
})
//Tools.js tool
const multer = require('multer')
const path = require('path')
const sd = require('silly-datetime')
const mkdirp = require('mkdirp')

let tools = {
    /*Package picture upload*/
    multer() {
        var storage = multer.diskStorage({
            //Configure the uploaded directory
            destination: async (req, file, cb) => {
                //1. Get the current date 20200703
                let day = sd.format(new Date(), 'YYYYMMDD')
                // static/upload/20200703
                let dir = path.join('static/upload', day)

                //2. Generate image storage directory by date
                Await mkdirp (DIR) // mkdirp is an asynchronous method

                cb(null, dir)
            },
            //Modify the uploaded file name
            filename: function (req, file, cb) {
                //Get the suffix of the uploaded file
                let extname = path.extname(file.originalname)
                cb(null, Date.now() + extname)
            }
        })
        var upload = multer({ storage: storage })
        return upload
    },
    md5() { }
}

module.exports = tools

Multi file upload:

//User.js multi file upload
const express = require('express')
const tools = require('../../model/tools')

var router = express.Router()

router.get('/', (req, res) => {
    Res.send ('user list ')
})
router.get('/add', (req, res) => {
    res.render('admin/user/add')
})

//Multi file upload
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

Recommended Today

C # regular implementation of UBB parsing class code

The parsed code can pass XHTML   one   Strict verification;It includes title, link, font, alignment, picture, reference, list and other functions  Ubb.ReadMe.htm UBB code description title [H1] title I [/ H1] Title I [H2] Title II [/ H2] Title II [H1] Title III [/ H1] Title III [H4] Title IV [/ H4] Title IV […]