el-upload中使用http-request

api文件

export const fileUpload = (params, config) =>
  request({
    url: '/api/blade-resource/oss/endpoint/put-file-attach',
    method: 'post',
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    timeout: 20 * 60 * 1000,
    data: params,
    ...config
  })

vue文件

<template>
  <el-upload
    ref="elUpload"
    :multiple="multiple"
    :accept="accept"
    :limit="limit"
    :file-list="fileList"
    :before-upload="beforeUpload"
    :on-progress="uploadProgress"
    :on-error="uploadError"
    :on-success="uploadSuccess"
    :http-request="uploadFile"
    :class="{ hide: isHide }"
    list-type="picture-card"
    action="void">
    <i slot="default" class="el-icon-plus"/>
    <div slot="file" slot-scope="{file}" class="wrap">
      <!-- {{ file }} -->
      <el-progress v-if="file.uploading" :percentage="file.uploadProgressPercent" type="circle"/>
      <video
        v-else-if="file.isVideo"
        :src="file.url"
        class="el-upload-list__item-thumbnail child"
        alt="上传的视频"
      />
      <img
        v-else
        :src="file.url"
        class="el-upload-list__item-thumbnail child"
        alt="上传的图片"
      >
      <span class="el-upload-list__item-actions">
        <span
          class="el-upload-list__item-delete"
          @click="handleRemove(file)"
        >
          <i class="el-icon-delete"/>
        </span>
      </span>
    </div>
  </el-upload>
</template>

js中有几个点需要注意下

  1. uploadFile函数使用async/await的话,需要在接口前添加await,不然会先执行后面的代码导致误判成功调用onSuccess

  2. uploadFile中添加onUploadProgress获取大致上传速度

  3. uploadFile、handleRemove的参数file有所不同

<script>
import axios from 'axios'
import fileBg from './uploadBg'
import { fileUpload, videoUpload, productDict } from '@/api/product'
const videoType = ['mp4', 'rmvb', 'flv', 'wmv', 'avi', 'mkv']
const imgType = ['jpg', 'png', 'jpeg', 'bmp', 'webp']
export default {
  name: 'MaterialUpload',
  props: {
    limit: { type: String | Number, default: 1 },
    multiple: { type: Boolean, default: false },
    accept: { type: String, default: '.jpg,.png' },
    files: { type: Array, default: () => [] }
  },
  data() {
    return {
      isHide: false,
      fileList: [],
      fileIds: [],
      cancel: {}
    }
  },
  watch: {
    // 监听父组件files,更新fileList,回填缩略图
    files: function(newVal) {
      if (newVal.length) {
        if (typeof newVal[0] !== 'object') return
        const ids = []
        newVal.forEach(item => {
          // console.log('fileList', item)
          if (item.id) ids.push(item.id)
          this.setUrl(item)
        })
        // this.fileList = newVal
        if (newVal.length >= this.limit) this.isHide = true
        this.fileList = Object.assign([], newVal)
        this.fileIds = ids
      } else {
        // 为全选删除服务
        this.fileList = []
        this.fileIds = []
        // this.isHide = false
      }
    }
  },
  created() {

  },
  methods: {
    // 设置文件缩略图url
    setUrl(item) {
      // 获取文件格式
      if (!item.extension)item.extension = ((item.name || item.orginalName || item.link || '').split('.')).pop().toLowerCase()
      // 视频及图片格式展示原有缩略图
      if (videoType.includes(item.extension)) {
        item.isVideo = true
        item.url = item.url || item.link
      } else if (imgType.includes(item.extension)) {
        item.url = item.url || item.link
      } else {
        // 其他格式展示存储或默认缩略图
        item.url = fileBg[item.extension] || fileBg.default
      }
    },
    // 用于上传前限制
    beforeUpload(file) {
      console.log('beforeUpload', file)
      const extension = file.name.split('.').pop()
      if (!this.accept.includes(extension)) {
        this.$message.warning(`请重新选择符合要求的文件`)
        return false
      }
      if (this.fileList.length + 1 >= this.limit) this.isHide = true
    },
    // 上传钩子
    onUploadProgress: fileObj => progressEvent => {
      console.log('progressEvent', progressEvent, fileObj)
      let complete = (progressEvent.loaded / progressEvent.total * 100 | 0)
      if (complete == 100) complete--
      fileObj.onProgress({ percent: complete })
    },
    // 上传时回调
    uploadProgress(event, file, fileList) {
      console.log('uploadProgress', event, file, fileList)
      file.uploading = true
      file.success = false
      file.uploadProgressPercent = event.percent // 调用进度条
      // this.fileList.push(file)
    },
    uploadError(err, file, fileList) {
      console.log('uploadError', err, file, fileList)
    },
    // 上传成功回调
    uploadSuccess(response, file, fileList) {
      console.log('uploadSuccess', response, file, fileList)
      file.uploading = false
      this.setUrl(file)
      this.setUrl(response)
      const link = response.link
      this.fileList.push(response)
      this.fileIds.push(response.attachId)
      this.$emit('onChange', { id: this.fileIds, link })
      if (this.fileList.length >= this.limit) this.isHide = true
    },
    // 上传函数
    uploadFile(file) {
      console.log('uploadFile', file)
      const formData = new FormData()
      formData.append('file', file.file)
      const CancelToken = axios.CancelToken
      fileUpload(formData, {
        onUploadProgress: this.onUploadProgress(file),
        cancelToken: new CancelToken(c => { this.cancel[file.file.uid] = c }) // 实例化一个CancelToken对象,赋值cancel方法
      }).then(res => {
        if (res.data.code == 200) {
          file.onSuccess(res.data.data)
        } else {
          file.onError(res.data.msg)
        }
      }).catch(err => {
        file.onError(err)
      })
    },
    // 删除接口
    handleRemove(file) {
      console.log('remove', file, this.fileList.indexOf(file))
      if (this.cancel[file.uid]) this.cancel[file.uid]()
      const index = this.fileList.indexOf(file)
      if (index !== -1) {
        this.fileList.splice(index, 1)
        this.fileIds.splice(index, 1)
        this.$emit('onChange', { id: this.fileIds })
      }
      if (this.fileList.length < this.limit) this.isHide = false
    }
  }
}
</script>
<style lang="scss" scoped>
.wrap{
  height: 100%;
  display:flex;
  justify-content:center;
}
.child{
  align-self:center;
}
// 附件上传隐藏样式
.hide {
  /deep/.el-upload {
    display: none;
  }
}
</style>

参考地址:el-upload自定义http-request 上传方法踩坑open in new window

Last Updated:
Contributors: haizhiguang