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

php Vue.js

ProL

2020-03-23

我有一个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和其他数据对象的地方,我没有发现任何问题。

第2788篇《POST文件以及表单数据Vue + axios》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
Gil斯丁 2020.03.23

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>

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android