【问题标题】:Sending a HTTP POST REQUEST with image and text发送带有图像和文本的 HTTP POST 请求
【发布时间】:2020-03-22 15:22:07
【问题描述】:

如何将 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.");
      }
    },

这是我的后端。

这会根据传递的数据创建文件夹,并且还会创建一个名为 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 是异步的,这就是它创建未定义文件夹的原因。

【问题讨论】:

    标签: javascript express http vue.js vuejs2


    【解决方案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 中间件,并允许您访问字段和图像/s。比如multer...

    【讨论】:

      【解决方案2】:

      对于第一部分,客户可以帮助你这个链接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);
      

      对于服务器部分不能帮助你这个链接 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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-08
        • 2016-12-06
        • 2019-03-15
        • 2020-05-09
        相关资源
        最近更新 更多