POST file along with form data Vue + axios

后端 未结 2 431
深忆病人
深忆病人 2020-12-31 17:58

I have a method for Vuejs component:

async submit () {
        if (this.$refs.form.validate()) {
          let formData = new FormData()
          formData.a         


        
2条回答
  •  一整个雨季
    2020-12-31 18:26

    So, I figured this one out in a simpler way:

        let rawData = {
                    name: this.name,
                    gender: this.gender,
                    dob: this.dob
                  }
                  rawData = JSON.stringify(rawData)
        let formData = new FormData()
              formData.append('avatar', this.avatarFile, this.avatarFile.name)
              formData.append('data', rawData)
        try {
                let response = await this.$axios.post('http://localhost:3003/api/test.php', formData, {
                  headers: {
                    'Content-Type': 'multipart/form-data'
                  }
             })
    

    test.php:

    $_POST = json_decode($_POST['data'],true);
    

    Note: I had an option of using:

    Object.keys(rawData).map(e => {
                formData.append(e, rawData[e])
              })
    

    but since I was dealing with nested objects (name: { first: '', last: ''} ) in rawData, I chose not to do that as it would require recursive methods on either client side or server side.

提交回复
热议问题