vue2.0+axios表单提交上传图片

需求:vue2+axios提交表单上传图片,发现网上很多的方法不好用,无法实现。下面是自己实验成功的方法。可以按照jquery提交表单的方法实现。这种方式可以成功上传图片,后台接收数据也是解析表单的形式


下面是一个小例子,仅只是方法, 部分代码

<form ref="form" enctype="multipart/form-data">

        //里面写一些需要传倒后台的input

        <input type="text" :value="sendInfo.email" name="email">       //name和后台接口接收该数据的字段对应

        <input type="file" name="avatar" accept="image/png,image/gif,image/jpeg">    //上传图片 accept:只允许传输图片

        <button @click.prevent.stop="changeInfo">提交<button>

</form>

import axios from 'axios'         //引入axios

//method里面的核心方法

changeInfo(){

        var formData = new FormData(this.$refs.form);         //获取表单数据

        let config = {   

          headers: {

            'Authorization': getCookie('fetoken')                           //根据需要添加头部token信息

            }         

        }

        axios.put(`user/${this.userId}/aver/`, formData,config)         

        .then(res => {

            if(res.data.error_code==0){

                this.tabshow=false

                    this.$emit('closeall',this.tabshow);

              }

        })

    },

猜你喜欢

转载自blog.csdn.net/qq_33168578/article/details/79290793