【问题标题】:POST file along with form data Vue + axiosPOST 文件连同表单数据 Vue + axios
【发布时间】:2019-03-15 23:58:09
【问题描述】:

我有一个 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 与其他数据对象一起使用的问题。

【问题讨论】:

  • 我相信你必须在每个变量上调用formData.append()。为什么会出现这样的问题?你不是在 axios 调用中声明它们吗?您只需在其他地方进行。
  • @acdcjunior 感谢您的提示

标签: php vue.js vue-component axios nuxt.js


【解决方案1】:

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

    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: ''} ),因此我选择不这样做,因为它需要客户端或服务器端的递归方法。

【讨论】:

  • 感谢分享这个
【解决方案2】:

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>

【讨论】:

  • 经过数小时的测试,这似乎是对我来说在另一端使用 PHP 脚本的唯一方法。
猜你喜欢
  • 2020-04-06
  • 2019-01-17
  • 2020-06-05
  • 2019-05-12
  • 1970-01-01
  • 2019-07-26
  • 2019-06-20
相关资源
最近更新 更多