参考文章多文件上传node包装接口分享_BUG不加糖的博客-CSDN博客_node 上传文件接口
问题:使用formdata去添加参数,一个参数上传一个文件,一个参数上传多个文件。关于文件的存储传递,后端接口的封装(觉得有必要现在就写篇文章来记录)上代码!!
方法一:
woody_mywlGo.post("/applyStore", mult, (req, res) => {
let formData = new FormData();
formData.append("userId", JSON.parse(req.session.user).id);
formData.append("brand", req.body.brand);
formData.append("storeIntroduce", req.body.storeIntroduce);
formData.append("storeName", req.body.storeName);
formData.append("storeStyle", req.body.storeStyle);
for (key in req.files) {
formData.append(key.split('_')[0],fs.createReadStream(req.files[key].path))
}
axios({
method: "post",
url: "http://110.40.212.128:8081/shop/storeApply/add",
data: formData,
headers: {
formData: formData.getHeaders(),
maxBodyLength: 1000000000,
},
})
.then((str) => {
res.send({ err: 0, msg: str.data });
})
.catch((err) => {
res.send({ err: -1, msg: err });
});
});
方法二:
woody_mywlGo.post("/applyStore", mult, (req, res) => {
let formData = new FormData();
formData.append("userId", JSON.parse(req.session.user).id);
formData.append("brand", req.body.brand);
formData.append("storeIntroduce", req.body.storeIntroduce);
formData.append("storeName", req.body.storeName);
formData.append("storeStyle", req.body.storeStyle);
for (key in req.files) {
if (req.files[key].length) {
for (let i = 0; i < req.files[key].length; i++) {
formData.append(
req.files[key][i].fieldName,
fs.createReadStream(req.files[key][i].path)
);
}
} else {
formData.append(key, fs.createReadStream(req.files[key].path));
}
}
axios({
method: "post",
url: "http://110.40.212.128:8081/shop/storeApply/add",
data: formData,
headers: {
formData: formData.getHeaders(),
maxBodyLength: 1000000000,
},
})
.then((str) => {
res.send({ err: 0, msg: str.data });
})
.catch((err) => {
res.send({ err: -1, msg: err });
});
});
这两种方法对应的前端的js代码,不同的是,上传对象的存储模式
方法一:
var formdataStore = new FormData();
addStore.addEventListener("click", function () {
addOPen.style.display = "block";
});
store_data.addEventListener("change", function () {
for (let i in store_data.files) {
formdataStore.append(`data_${i}`, store_data.files[i]);
}
});
方法二:
var formdataStore = new FormData();
addStore.addEventListener("click", function () {
addOPen.style.display = "block";
});
store_data.addEventListener("change", function () {
for (let i in store_data.files) {
formdataStore.append(`data`, store_data.files[i]);
}
});
选择其中任意一种都可以实现单文件和多文件一起上传的功能了!下班!