【问题标题】:Send post request form data with image to back end将带有图像的发布请求表单数据发送到后端
【发布时间】:2020-04-22 03:15:44
【问题描述】:

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

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 写错了,但我不知道该怎么做。任何人都可以纠正它吗?

【问题讨论】:

  • 你能分享后端代码吗?请检查formData有什么用
  • 我的后端代码只是从前端读取数据。但是,前端只发送[Object Object]。我读到 Formdata 发送密钥/对值集,但由于我的 Post 请求更复杂,它不适合吗?

标签: reactjs axios multipartform-data


【解决方案1】:

您不能将对象附加到 formData,您可以在 this answer 阅读更多内容。试试这个

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)
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-24
    • 1970-01-01
    • 2022-09-23
    • 1970-01-01
    • 2018-01-27
    • 1970-01-01
    • 1970-01-01
    • 2015-10-05
    相关资源
    最近更新 更多