首页 > 解决方案 > 将带有图像的发布请求表单数据发送到后端

问题描述

目前这是我关于向后端发送帖子请求的代码(在使用 axios 的 reactjs 中):

sendDataToBackEnd = async () => {
      await axios.post(
        'http://localhost:9000/message',
         {
           testPlace: 
             {
               country: this.state.countryTest,
               city: this.state.cityTest,
               testSite: this.state.testSite
             },
           personalInformation:
             {
               name: this.state.name,
               birthday:this.state.birthday),
               gender:this.state.gender,
               address:this.state.address,
             }
         }
        ,
        { headers: { 
          'Content-Type': 'application/json'
        } }
      ).then((response) => {
          // got the response. do logic
      })
  }

现在,我还需要将人的图像发送到后端进行保存。我想我必须发送表单数据。但是,我在将上面的信息发送到后端时遇到问题。这是我的做法:

sendDataToBackEnd = async () => {
    let formData = new FormData();
    formData.append('testPlace',
             {
               country: this.state.countryTest,
               city: this.state.cityTest,
               testSite: this.state.testSite
             })
    formData.append('personalInformation',
             {
               name: this.state.name,
               birthday:this.state.birthday),
               gender:this.state.gender,
               address:this.state.address,
             })
    formData.append('file',this.state.picture)
      await axios.post(
        'http://localhost:9000/message',
         formData
        ,
        { headers: { 
          'Content-Type': 'multipart/form-data'
        } }
      ).then((response) => {
          // got the response. do logic
      })
  }

但是,当我检查发送到后端的请求时,它显示 [Object Object]。我想我的 testPlace 和 personalInformation 的 formData 写错了,但我不知道该怎么做。任何人都可以纠正它吗?

标签: reactjsaxiosmultipartform-data

解决方案


您不能将对象附加到 formData 您可以在此答案中阅读更多内容。试试这个

let formData = new FormData();
formData.append('file',this.state.picture)
formData.append('testPlace[country]', this.state.countryTest)
formData.append('testPlace[city]', this.state.cityTest)
formData.append('testPlace[testSite]', this.state.testSite)

formData.append('personalInformation[name]', this.state.name)
formData.append('personalInformation[birthday]', this.state.birthday)
formData.append('personalInformation[gender]', this.state.gender)
formData.append('personalInformation[address]', this.state.address)
...

推荐阅读