POST 文件和表单数据 Vue + axios

POST file along with form data 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 与其他数据对象一起使用的任何问题。

所以,我用一种更简单的方法解决了这个问题:

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

注意:我可以选择使用:

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

但由于我在处理 rawData 中的嵌套对象 (name: { first: '', last: ''} ),我选择不这样做,因为它需要在客户端或服务器端使用递归方法。

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>