当前位置: 代码迷 >> 综合 >> vue axios 实现上传文件
  详细解决方案

vue axios 实现上传文件

热度:84   发布时间:2023-12-17 20:40:02.0

1 新建一个用来上传文件的axios,不同普通请求后台的axios,因为上传文件不能手动设置请求头

     var uploadAxios = axios.create({}),
      Vue.prototype.$uploadAxios = uploadAxios;  

   注意: 不要设置请求头headers: {'Content-Type': '......'},
   因为上传文件时请求头的mulpipart/formData格式需要boundary,  boundary是浏览器自动给请求头内容添加的
   如果设置了请求头header, boundary就会被覆盖,  然后上传时就没有数据传到后台和后台报错 “no multipart boundary was found” ;

2  获取文件的值

<form>
    <input type="file" @change="selectFile($event)">
    <input type="button" @click="submittFile($event)">
</form>

data: function(){   
    return { file: "", }  // 保存文件的值
}
selectFile: function (event){
       this.file = event.target.value 
}

3 提交文件到后台
       FormData类型其实是在XMLHttpRequest 2级定义的,它是为序列化表以及创建与表单格式相同的数据(当然是用于XHR传输)提供便利。

 submitFile: function (event){
       event.preventDefault();
       var formData = new FormData(); 
       formData.append("file", this.file);   // 添加键值对到formData, 用append()方法添加方式;
       formData.append('myname', 'rmy');

      // 上传文件不用设置请求头, 浏览器会自动设置请求头和boundary
       this.$uploadAxios.post('url', formData).then(res=>{ 
            console.log(res)
       }).catch(err=>{
           console.log(err);
       })
}