我有一个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'
              }
         })

测验php:

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

Note:我可以 Select 使用:

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

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

Vue.js相关问答推荐

VITE:无法为VUE单文件组件加载URL

vuetify/mdi 不显示图标

有什么理由不在 vue3 中使用