POST文件以及表单数据Vue + axios

我有一个Vuejs组件的方法:

async submit () {
        if (this.$refs.form.validate()) {
          let formData = new FormData()
          formData.append('userImage', this.avatarFile, this.avatarFile.name)
          this.avatarFile = formData
          try {
            let response = await this.$axios.post('http://localhost:3003/api/test.php', {
              avatar: this.avatarFile,
              name: this.name,
              gender: this.gender,
              dob: this.DOB,
            }, {
              headers: {
                'Content-Type': 'multipart/form-data; boundary=' + formData._boundary
              }
            })
            if (response.status === 200 && response.data.status === 'success') {
              console.log(this.response)
            }
          } catch (e) {
           console.log(e)
          }
        }
      }

在中test.php,我json_decode(file_get_contents("php://input"), TRUE);用来读取数据作为$_POST变量。

虽然我能读namegenderdob正确,我不能获取avatar正常。

有相同的解决方案吗?

注意:formData.append(.., ..)由于我打算处理14个以上的变量,因此我不会附加每个变量。

主持人注意:在使用formData和其他数据对象的地方,我没有发现任何问题。

Gil斯丁2020/03/23 12:03:14

PHP(process.php)

<?php
    $data = array(
        "post"  => $_POST,
        "files" => $_FILES
    );

    echo json_encode($data);
?>

Vue和表单HTML

let vm = new Vue({
    el: "#myApp",
    data: {
        form: {}
    },
    methods: {
        submit: async function (e) {
            e.preventDefault();

            /* formData */
            var formData = new FormData( this.$refs.formHTML );

            /* AJAX request */
            await axios({
                method: "post",
                url: "process.php",

                data: formData,

                config: { headers: { "Content-Type": "multipart/form-data" } }
            })

            /* handle success */
            .then( response => { console.log(response.data); } )

            /* handle error */
            .catch( response => { console.log(response) } );
        }
    }
});
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.js"></script>

<div id="myApp" >

    <form @submit="submit" ref="formHTML" >

        Name: <input type="text" name="name" v-model="form.name" /><br />

        Gender:
        <input type="radio" name="gender" value="male" v-model="form.gender" /> Male
        <input type="radio" name="gender" value="female" v-model="form.gender" /> Female <br />

        File: <input type="file" name="upload" v-model="form.upload" /><hr />

        <input type="submit" name="submit" value="Submit" />

    </form>

</div>