Vue Element 上传

39 min read

Element方法

<el-form-item label="文件上传" prop="fileList">
  <el-upload
    class="upload-demo"
    :action="upLoadUrl"
    :before-remove="beforeRemove"
    :on-remove="upLoadRemove"
    :on-success="upLoadSuccess"
    :on-preview="downLoadFile"
    :file-list="fileList">
    <el-button size="small" type="primary">上传附件</el-button>
  </el-upload>
</el-form-item>

页面方法

// 用于构建文件对象
class Attach {
  constructor (file) {
    this.name = file.fileName
    this.url = file.filePath
    this.file = file
  }
}

// 文件上传成功后回调
upLoadSuccess(data) {
  if (data && data.code === 0) {
    // 将回调的后台文件对象转为前端的文件对象
    this.fileList.push(new Attach(data.fileModel))
  } else {
    this.$message.error(data.msg)
  }
},
// 点击文件进行下载
downLoadFile(file) {
  const downloadLoading = this.$loading({
    lock: true,
    text: '拼命下载中...',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)'
  });
  request({
    url: '/detection/file/download' + file.url,
    method: 'get',
    responseType: 'blob'
  }).then(response => {
    if (!response) {
      downloadLoading.close()
      return
    }
    let url = window.URL.createObjectURL(new Blob([response]))
    let link = document.createElement('a')
    link.style.display = 'none'
    link.href = url
    link.setAttribute('download', file.name)
    document.body.appendChild(link)
    link.click()
    downloadLoading.close()
  }).catch(err => {
    this.$message.error(err)
    downloadLoading.close()
  })
}