簡體   English   中英

發送帶有圖像和文本的 HTTP POST REQUEST

[英]Sending a HTTP POST REQUEST with image and text

如何將圖像與 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 是異步的,這就是它創建未定義文件夾的原因。

對於第一部分,客戶可以幫助您此鏈接如何使用 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 將圖像文件作為 API 響應發送

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

和關於這個http://expressjs.com/en/api.html#res.sendFile 的官方文檔

您看到的行為原因是您向同一路由發送了兩個不同的請求。 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 ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM