1、客户端
<form action="http://localhost:3000/profile" method="post" enctype="multipart/form-data"> <input type="file" name="avatar" /> <input type="submit" value="av2tar" /> </form>
2、服务器端
//假设你的express 服务器已经跑起来了 var express = require('express'); const fs = require('fs'); const path = require('path'); var controllers = path.join(path.resolve(__dirname, '..'), 'controllers'); var uploadDir = path.join(path.resolve(__dirname, 'uploads')); var router = express.Router(); var multer = require('multer'); var storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, './uploads') //自己定义目录 }, filename: function (req, file, cb) { console.log(file) cb(null, file.originalname + '-' + Date.now()) /* {
fieldname: 'avatar', originalname: 'flink-1.8.0-bin-scala_2.12.tgz', encoding: '7bit', mimetype: 'application/gzip'
} */ } }) var upload = multer({ storage: storage }) /* GET users listing. */ router.post('/', upload.single('avatar'), function(req, res, next) { res.send('Upload success...'); }); module.exports = router;
官网网站:https://www.npmjs.com/package/multer