multer
//安装multer
npm install --save multer
1.改变form表单的enctype
enctype="multipart/form-data"
设置file的名字 例:pic
2.引入multer
const multer = require("multer");
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "static/uploads"); //指定上传保存的路径
},
// 修改上传后的文件名
filename: function (req, file, cb) {
// cb(null, file.fieldname + '-' + Date.now())
// 1.获取后缀名
let extname = path.extname(file.originalname);
// 2.根据时间戳 生成文件名
cb(null, Date.now() + extname);
},
});
var upload = multer({ storage: storage }
);
3.接收
router.post("/toAdd",**upload.single("pic")**, (req, res) => {
res.send({
file:req.file
});
}
);
例子:
//1 新建tools.js文件,添加文件上传模块封装
const path = require("path");
const multer = require("multer");
let tools = {
/**
* 配置上传文件插件-multer
*/
setMulter() {
let storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "static/uploads"); //指定上传保存的路径
},
// 修改上传后的文件名
filename: function (req, file, cb) {
// cb(null, file.fieldname + '-' + Date.now())
// 1.获取后缀名
let extname = path.extname(file.originalname);
// 2.根据时间戳 生成文件名
cb(null, Date.now() + extname);
},
});
let upload = multer({ storage: storage });
return upload;
},
};
module.exports = tools;
2.在需要用的文件中引入const tools=require("../../modal/tools");
3.在要接收上传的post请求的第二个参数调用 tools.setMulter().single("pic")
router.post("/toAdd",tools.setMulter().single("pic"), (req, res) => {
//获取表单传过来的数据
res.send({
file: req.file,
});
});