expressはmultierと結合してファイルアップロード機能を実現します. 2648 ワード node.js express es 6 javascript 先端 ファイルアップロード: : : :<br/><br/> <input type="submit" value=" "/> </form></code></pre> <pre><code>// nav.js const express = require('express') const tools = require('../../model/tools') router.post('/doAdd', tools.multer().single('pic'), (req, res) => { // res.send({ body: req.body, file: req.file }) })</code></pre> <pre><code>// 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. await mkdirp(dir) // mkdirp cb(null, dir) }, // filename: function (req, file, cb) { // let extname = path.extname(file.originalname) cb(null, Date.now() + extname) } }) var upload = multer({ storage: storage }) return upload }, md5() { } } module.exports = tools</code></pre> <p> :</p> <pre><code>// 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</code></pre> </article> </div> </div> javascriptシミュレーションC〓String.format関数機能コードを実現します.