项目用到了ElementUI作为UI框架,在做一些上传图片的功能时也自然用到了upload组件。
upload组件自带有异步上传图片的功能的,当然想用自己的接口也是可以的,只需要在before-upload事件里调用自己的接口,并在最后返回false,组件就不会调用自己的上传方法。但是action参数必须要有,任意填或为空都可以。

<el-upload
  class="avatar-uploader"
  action=""
  :before-upload="beforePicUpload"
  :show-file-list="false">
  <el-button type="primary" icon="el-icon-plus" circle ></el-button>
</el-upload>
...
    beforePicUpload (file) {
      const isLt1M = file.size / 1024 / 1024 < 1
      if (!isLt1M) {
        this.$message.error('上传头像图片大小不能超过 1MB!')
        return false
      }
	  //这里是我将file作为参数传给了我的接口
      this.$api.addSwiper([file]).then(res => {
        if (res.result) {
          this.$message.success('上传成功')
          this.renderData()
        } else {
          this.$message.error('上传失败')
        }
      })
      return false
    },
...

传给接口后通过FormData以表单的形式传递给后台

...
  addSwiper: (params) => {
    let [ file ] = params
    let fd = new FormData()
    fd.append('file', file)
    return request({
      url: `...`,
      method: 'post',
      data: fd
    })
  },
...