[英]Why is my array of files not appending to FormData?
我已经坚持了三天。 我已经在该网站上尝试了几乎所有解决方案,甚至在其他网站上寻求帮助。
我正在尝试以FormData对象作为正文发送发布请求。 一切正常,除了我的图像数组以未定义/空的形式到达服务器这一事实之外,这导致文档以空数组[]作为图像键的值保存到数据库中。
在Postman上测试路由,它可以完美工作并保存我发送的图像阵列。 所以我的前端代码有问题。 是的,我输入的HTML文件的名称与后端的upload.array(name,number)相同。 是的,猫鼬模型将key:value对设置为数组。 是的,所有multer的设置都完美(在单次上传中效果很好,而在与Postman进行测试时,可以多次上传)。
据我所知,问题肯定出在下面的代码中。 似乎我的文件数组没有追加到FormData。
// POST FUNCTIONALITY
//initializing Post Article variables
let formContent = "";
let fileInput = [];
//listening for value changes in the Post Article form
function formDataChange() {
document.getElementById("tArea").addEventListener("change", function(){
formContent = document.getElementById("tArea").value;
});
document.querySelector("input[type='file']").addEventListener("change", function(){
fileInput = Array.from(document.querySelector("input[type='file']").files);
console.log(fileInput); //this console log outputs the array of files showing that the event listener at least is working properly
});
};
formDataChange();
//listen for POST button
function listenPostArticle() {
document.getElementById("postArticle").addEventListener("click", postArticle);
};
listenPostArticle();
//fire off POST request
function postArticle () {
let formdata = new FormData();
formdata.append("content", formContent);
formdata.append("jwt", token);
fileInput.forEach((f) => {
formdata.append("image[]", f);
})
let req = new Request("http://localhost:8080/api/articles/", {method: 'POST', body: formdata,
headers:{'Authorization': "Bearer " + token}});
fetch(req)
.then(res => res.json())
.then((data) => {
console.log(data);
res.redirect("http://localhost:5500");
})
}
猫鼬架构:
const mongoose = require("mongoose");
const ArticleSchema = new mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
content: {type: String, required: true},
image: {type: []},
jwt: {type: String}
});
module.exports = Article = mongoose.model("article", ArticleSchema);
路线:
router.post("/", upload.array("image", 5), (req, res) => {
const newArticle = new Article({
_id: mongoose.Types.ObjectId(),
content: req.body.content,
image: req.files,
jwt: req.body.jwt
});
newArticle
.save()
.then(result => {
res.json({ message: "Article posted!"});
})
});
在标题中添加multipart / form-data
let req = new Request("http://localhost:8080/api/articles/", {method: 'POST', body: formdata,
headers:{'Authorization': "Bearer " + token,'Content-Type': 'multipart/form-data'}});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.