el-upload 与 FormData上传文件

来源:互联网 发布:游戏画面 知乎 编辑:程序博客网 时间:2024/04/29 00:08

最近在用el-upload做上传图片的功能,用的el-uplod中的点击上传做。但是
点击上传的时候。不会触发action中的post请求,所以就干脆在on-change函数里写入原生的FormData上传文件的方法。

getImgUrl () {    var fileValue = document.querySelector('.el-upload .el-upload__input')    var fd = new window.FormData()    // 配置post请求的参数。参数名file,后面跟要传的文件,参数名fileType,值为category(看后端的具体要求)    fd.append('fileType', 'category')    fd.append('file', fileValue.files[0])    var xhr = new XMLHttpRequest()    xhr.open('POST', url, true)    // url就是要发送的post请求的地址    xhr.send(fd)    xhr.onload = () => {      if (xhr.status === 200) {        this.imgurl = JSON.parse(xhr.responseText).url        console.log(this.imgurl)      }    }  },  handleOnchange () {    this.getImgUrl()  }

还好el-upload里面有on-change这个回调函数。在on-change这个回调函数中直接用原生的FormData和XML来实现请求的发送。最后会拿到xhr.responseText这个字符串文本,需先将文本转化为json对象。然后用.url拿到服务器请求回来的url图片地址。

这里值得注意。在xhr.onload要写成箭头函数的形式。this.imgurl中的this才是Vue实例对象。如果把xhr.onload写成ES5的形式

xhr.onload = function () {    console.log(this)}

这里的this只的就是xml对象了。注意vue项目中的this指向问题

el-upload中的点击上传不会触发action写的post请求。但是el-upload的用户头像上传就会触发action中的post请求。可能自己的结论不准确。望朋友们多多提意。

原创粉丝点击