为什么我的文件数组未追加到FormData?

时间:2018-08-05 02:36:49

标签: javascript mongodb express mongoose multer

我已经坚持了三天。我已经在该网站上尝试了几乎所有的解决方案,甚至在其他网站上寻求帮助。

我正在尝试以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!"}); 
    })
});

Screenshot of Postman working successfully. Key field for images is "image"

1 个答案:

答案 0 :(得分:0)

在标题中添加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'}});