前端:1.准备表单数据,提交到服务端 2.创建表单数据实例
let reqData = new FormData();
reqData.append("cover", this.coverFile); //图片
reqData.append("md", this.mdFile);//md文件
reqData.append("title", this.articleForm.title); //表单文本
reqData.append("introduction", this.articleForm.introduction);//表单文本
reqData.append("tag", this.articleForm.tag);//表单文本
发送axios请求:
try {
let res = await axios.post("/articles/addArticle", reqData);
console.log(res, "res");
} catch (error) {
console.log("err");
}
});
后端node+express+multer接收数据:
//1
//indx.js入口文件
const express = require("express");
const app = express();
// 监听路由中间件
app.use("/articles", require("./router/article"));
//2
//article.js文件
router.get("/getArticle", article.getArticle);
//3
//引入所需要的模块
const multer = require("multer"); //处理表单数据
const fs = require("fs");
const upload = multer({
storage: multer.diskStorage({
//设置文件存储位置
destination: function (req, file, cb) {
let date = new Date();
let year = date.getFullYear();
let month = (date.getMonth() + 1).toString().padStart(2, "0");
let day = date.getDate();
// 设置存储路径,设置在 public 文件下
let dir = `public/uploads/${file.fieldname}/${year}${month}${day}`;
//判断目录是否存在,没有则创建
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, {
recursive: true,
});
}
cb(null, dir);
},
//设置文件名称
filename(req, file, cb) {
// 重命名文件名,防止重复
let fileName =
file.fieldname + "-" + Date.now() + "-" + file.originalname;
cb(null, fileName);
},
}),
});
// 常用的两方法:多选用 array(),单选用single(),混合表单文件fields 注意name要与前端传过来的一致
const multipleFile = upload.fields([
{ name: "cover", maxCount: 1 },
{ name: "md", maxCount: 1 },
]);
// const multipleFile = upload.array('file', 3) --数组
// const multipleFile = upload.single('file') --单文件
let addArticle = (req, res, next) => {
multipleFile(req, res, (err) => {
if (err instanceof multer.MulterError) {
console.log("---errMulterError---", err);
} else if (err) {
console.log("---err---", err);
}
console.log("req.file--", req.files, "req.body:", req.body);
let sql = `insert into article(cover, title, content, tag,introduction)
value(?,?,?,?,?); `;
let sqlArr = [urlCover, title, urlMd, tag, introduction];
let callBack = (err, data) => {
if (err) {
console.log("---连接出错了----");
res.send({
code: 400,
msg: "errer",
});
} else {
res.json({
code: 200,
msg: "添加成功",
data: data,
});
}
};
dbConfig.sqlConnect(sql, sqlArr, callBack);
});
};