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

时间:2019-11-27 06:01:07

标签: javascript express http vue.js vuejs2

如何将VueJs中的图像和文本发送到后端ExpressJ?

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

注意 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.");
      }
    },

这是我的后端。

这将基于传递的数据创建文件夹,并且还将创建一个名为 undefined 的文件夹

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是异步的,所以它创建了未定义的文件夹。

2 个答案:

答案 0 :(得分:1)

您看到的行为原因是,您正在向同一路由发送两个不同的请求。第一个包括ALBUM和DESCRIPTION表单字段值,但不包括文件。第二个(在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 ...

答案 1 :(得分:0)

在第一部分中,客户可以为您提供此链接How to post image with fetch?

const fileInput = document.querySelector('#your-file-input') ;
const formData = new FormData();

formData.append('file', fileInput.files[0]);

    const options = {
      method: 'POST',
      body: formData,
      // If you add this, upload won't work
      // headers: {
      //   'Content-Type': 'multipart/form-data',
      // }
    };

    fetch('your-upload-url', options);

并且对于Seerver部分无法帮助您此链接 Node Express sending image files as API response

app.get('/report/:chart_id/:user_id', function (req, res) {
    res.sendFile(filepath);
});

和与此有关的官方文档 http://expressjs.com/en/api.html#res.sendFile