Vue 实现文件的上传

  要把文件上传的web,需要分几步?

  答:三步

  第一步:创建一个上传文件的标签 

  <input type="file" id="fileExport" @change="handleFileChange" ref="inputer">
  由于是在vue中,考虑到获取节点,所以给标签添加一个ref,方便获取属性并给标签添加事件
  
  第二步:改动事件
  
  handleFileChange (e) {
    let inputDOM = this.$refs.inputer;
    this.file = inputDOM.files[0];// 通过DOM取文件数据
    let size = Math.floor(this.file.size / 1024);//计算文件的大小 
    this.formData=new FormData(); //new一个formData事件
    this.formData.append("file",this.file); //将file属性添加到formData里
    //此时formData就是我们要向后台传的参数了
  }
  
  第三步:上传formData    
  this.$http({
    url:this.HOST + api.upload,
    data:formData, //在此处上传文件
    method: "post",
    headers:{
      'Content-Type':'multipart/form-data' //值得注意的是,这个地方一定要把请求头更改一下
    }
    }).then(function(res){
       console.log(res,"此处应该是请求成功的回调")  
    }.catch(function(req){
        console.log(req,"请求失败的回调,自己看看为啥失败")
    })
})
  
 
  

猜你喜欢

转载自www.cnblogs.com/-moon/p/11375123.html