发送带有图像和文本的 HTTP POST REQUEST

用户12056490

如何将图像与 VueJs 中的文本一起发送到我的后端 ExpressJs?

现在,我所做的是创建两个 http post 请求

注意this.albumName 和 this.albumDesc 只是文本,而 formData 是一个图像。

createAlbum() {
      const formData = new FormData();
      for (let file of Array.from(this.myAlbumImages)) {
        formData.append("files", file);
      }

      if (this.albumName) {
        axios
          .post("http://localhost:9001/image/album", {
            ALBUM: this.albumName,
            DESCRIPTION: this.albumDesc
          })
          .then(resp => console.log(resp))
          .catch(err => console.log(err));
        setTimeout(function() {
          axios
            .post("http://localhost:9001/image/album", formData)
            .then(resp => console.log(resp))
            .catch(err => console.log(err));
        }, 3000);

        this.albumName = "";
        this.albumDesc = "";
      } else {
        alert("Please fill the above form.");
      }
    },

这是我的后端。

这会根据传递的数据创建文件夹,并且还会创建一个命名的未定义文件夹

router.post('/album', (req, res) => {
let sql = "INSERT INTO GALLERY SET ALBUM = ?, DESCRIPTION = ?";
let body = [req.body.ALBUM, req.body.DESCRIPTION]
myDB.query(sql, body, (error, results) => {
    if (error) {
        console.log(error);
    } else {
        let directory = `C:/Users/user/Desktop/project/adminbackend/public/${req.body.ALBUM}`;
        fse.mkdirp(directory, err => {
            if (err) {
                console.log(err);
            } else {
                console.log(directory);
            }
        })
    }
})

我认为这是因为 NodeJS 是异步的,这就是它创建未定义文件夹的原因。

米哈尔·列维

您看到的行为原因是您向同一路由发送了两个不同的请求。1st 包括“专辑”和“描述”表单字段值,但不包括文件。第二个(内部setTimeout)将只包含文件而不包含其他字段,因此引用它们req.body.ALBUM会返回undefined

您可以在一个请求中发送所有数据(文本字段和文件)。只需这样做:

const formData = new FormData();
for (let file of Array.from(this.myAlbumImages)) {
  formData.append("files", file);
}
formData.append("ALBUM", this.albumName);
formData.append("DESCRIPTION", this.albumDesc);
axios.post("http://localhost:9001/image/album", formData)
     .then(resp => console.log(resp))
     .catch(err => console.log(err));

FormData始终使用内容类型multipart/form-data要在服务器端解析它,您需要解析多部分表单的 Express 中间件,并让您可以访问字段和图像。例如multer ...

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章