【问题标题】:Vue Custom input file component could not be submitted correctlyVue自定义输入文件组件无法正确提交
【发布时间】:2018-12-03 22:19:53
【问题描述】:

我有一个用于浏览文件的组件,用于选择要上传的文件。 这是我的组件:

       <template>
        <label class="file-select">
          <div class="select-button">
            <span v-if="value">Selected File: {{value.name}}</span>
            <span v-else>Select File</span>
          </div>
          <input type="file" @change="handleFileChange"/>
        </label>
      </template>

      <script>
      export default {
        props: {
          value: File
        },

        methods: {
          handleFileChange(e) {
            this.$emit('input', e.target.files[0])
          }
        }
      }
      </script>

这是我使用组件的方式:

            <p>Select Image: <bim-fileinput v-model="file"></bim-fileinput></p>

这是我使用 axios 提交文件的方式:

 submit: function(){
            console.log(localStorage.getItem('token'));
            axios.post('/api/employees', {
               picture: this.file,   

            }, { headers: { Authorization: 'Bearer '.concat(localStorage.getItem('token')) }, 'Content-Type': 'multipart/form-data' })
            .then(response => {
               router.push({ name: "IndexEmployees"});
            }).catch(error => {
                console.log(error.message);
            });
        }

提交后,在控制器中我得到图片属性,但作为一个空数组。 所以我尝试使用控制台打印它。 console.log('文件'+ JSON.stringfy(this.file))

我有文件 {} 作为一个空对象。

所以我需要弄清楚我的代码中的问题在哪里,或者如何正确解决。

提前致谢。

【问题讨论】:

    标签: laravel-5 vue.js vuejs2 vue-component quasar-framework


    【解决方案1】:

    this.fileFile 的实例,json 编码时总是{}

    axios中的问题,必须使用FormData发送文件。

    const formData = new FormData();
    formData.append('picture', this.file);
    axios.post('/api/employees', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          // ...
        }
    }) // ...
    

    【讨论】:

      猜你喜欢
      • 2017-11-22
      • 2015-05-22
      • 2020-06-09
      • 1970-01-01
      • 1970-01-01
      • 2021-06-19
      • 2021-02-09
      • 2018-10-03
      • 2016-12-14
      相关资源
      最近更新 更多