npm i multer
const multer = require('multer')
const upload = multer({dest:'public/'}) //设置文件上传路径
//用中间件的方式挂载到路由上controller中间件之前
router.post('/headimg',verfiyToken,upload.single('headimg'),userController.headimg)
controller
const fs = require('fs')
const {promisify} = require('util')
const rename = promisify(fs.rename)
// 上传完成后默认收到的是二进制文件需要手动使用fs模块进行重命名
exports.headimg= async (req,res) => {
console.log(req.file);
const fileArr = req.file.originalname.split('.')
const fileType = fileArr[fileArr.length - 1]
try {
await rename('./public/'+req.file.filename,'./public/'+req.file.filename+'.'+fileType)
res.status(201).json({filepath:req.file.filename+'.'+fileType})
} catch (error){
res.status(500).json(error)
}
}