fileUpload.vue 6.78 KB
Newer Older
1 2
<template>
  <div class="upload-file">
3
    <el-upload multiple :action="uploadFileUrl" :before-upload="handleBeforeUpload" :file-list="fileList" :limit="limit" :disabled="disabled" :on-error="handleUploadError" :on-exceed="handleExceed" :on-success="handleUploadSuccess" :show-file-list="false" :headers="headers" class="upload-file-uploader" ref="upload">
4
      <!-- 上传按钮 -->
5
      <el-button size="mini" type="primary" :disabled="disabled">{{ $t("选取文件") }}</el-button>
6 7 8 9 10 11 12 13 14 15 16 17 18 19
      <!-- 上传提示 -->
      <div class="el-upload__tip" slot="tip" v-if="showTip">
        请上传
        <template v-if="fileSize">
          大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>
        </template>
        <template v-if="fileType">
          格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b>
        </template>
        的文件
      </div>
    </el-upload>

    <!-- 文件列表 -->
20 21
    <transition-group class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear" tag="ul">
      <li :key="index" v-for="(file, index) in fileList">
22
        <div class="imgItem" v-if="checkFileIsImage(file.url)">
23 24 25 26
          <el-image style="width: 200px; height: 100px" :src="file.url" :preview-src-list="[file.url]"> </el-image>
          <div class="ele-upload-list__item-content-action">
            <el-button size="mini" type="danger" :disabled="disabled" @click="handleDelete(index)">删除</el-button>
          </div>
27 28 29 30 31 32
        </div>
        <div class="el-upload-list__item ele-upload-list__item-content" v-else>
          <el-link :href="`${file.url}`" :underline="false" target="_blank">
            <span class="el-icon-document"> {{ getFileName(file.name) }} </span>
          </el-link>
          <div class="ele-upload-list__item-content-action">
33
            <el-button size="mini" type="danger" :disabled="disabled" @click="handleDelete(index)">删除</el-button>
34 35 36 37 38 39 40 41
          </div>
        </div>
      </li>
    </transition-group>
  </div>
</template>

<script>
42
import { getToken } from "@/utils/auth"
43 44 45 46 47 48 49 50 51

export default {
  name: "FileUpload",
  props: {
    // 值
    value: [String, Object, Array],
    // 数量限制
    limit: {
      type: Number,
52
      default: 5
53 54 55 56
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
57
      default: 5
58 59 60 61
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
62
      default: () => ["doc", "xls", "ppt", "txt", "pdf"]
63 64 65
    },
    disabled: {
      type: Boolean,
66
      default: false
67 68 69 70
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
71 72
      default: true
    }
73 74 75 76 77 78 79 80
  },
  data() {
    return {
      number: 0,
      uploadList: [],
      baseUrl: process.env.VUE_APP_BASE_API,
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/admin-api/infra/file/upload", // 上传的文件服务器地址
      headers: {
81
        Authorization: "Bearer " + getToken()
82
      },
83 84
      fileList: []
    }
85 86 87 88 89
  },
  watch: {
    value: {
      handler(val) {
        if (val) {
90
          let temp = 1
91
          // 首先将值转为数组
92
          const list = Array.isArray(val) ? val : this.value.split(",")
93 94 95
          // 然后将数组转为对象数组
          this.fileList = list.map((item) => {
            if (typeof item === "string") {
96
              item = { name: item, url: item }
97
            }
98 99 100
            item.uid = item.uid || new Date().getTime() + temp++
            return item
          })
101
        } else {
102 103
          this.fileList = []
          return []
104 105 106
        }
      },
      deep: true,
107 108
      immediate: true
    }
109 110 111 112
  },
  computed: {
    // 是否显示提示
    showTip() {
113 114
      return this.isShowTip && (this.fileType || this.fileSize)
    }
115 116 117 118 119 120
  },
  methods: {
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      // 校检文件类型
      if (this.fileType) {
121
        let fileExtension = ""
122
        if (file.name.lastIndexOf(".") > -1) {
123
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1).toLowerCase()
124 125
        }
        const isTypeOk = this.fileType.some((type) => {
126 127 128 129
          if (file.type.indexOf(type) > -1) return true
          if (fileExtension && fileExtension.indexOf(type) > -1) return true
          return false
        })
130
        if (!isTypeOk) {
131 132
          this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`)
          return false
133 134 135 136
        }
      }
      // 校检文件大小
      if (this.fileSize) {
137
        const isLt = file.size / 1024 / 1024 < this.fileSize
138
        if (!isLt) {
139 140
          this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB!`)
          return false
141 142
        }
      }
143 144 145
      this.$modal.loading("正在上传文件,请稍候...")
      this.number++
      return true
146 147 148
    },
    // 文件个数超出
    handleExceed() {
149
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`)
150 151 152
    },
    // 上传失败
    handleUploadError(err) {
153 154
      this.$modal.msgError("上传文件失败,请重试")
      this.$modal.closeLoading()
155 156 157 158
    },
    // 上传成功回调
    handleUploadSuccess(res) {
      // todo 接口返回值没有文件名
159
      this.uploadList.push({ name: res.data, url: res.data })
160
      if (this.uploadList.length === this.number) {
161 162 163 164 165
        this.fileList = this.fileList.concat(this.uploadList)
        this.uploadList = []
        this.number = 0
        this.$emit("input", this.listToString(this.fileList))
        this.$modal.closeLoading()
166 167 168 169
      }
    },
    // 删除文件
    handleDelete(index) {
170 171
      this.fileList.splice(index, 1)
      this.$emit("input", this.listToString(this.fileList))
172 173 174 175
    },
    // 获取文件名称
    getFileName(name) {
      if (name.lastIndexOf("/") > -1) {
176
        return name.slice(name.lastIndexOf("/") + 1)
177
      } else {
178
        return ""
179 180 181 182
      }
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
183 184
      let strs = ""
      separator = separator || ","
185
      for (let i in list) {
186
        strs += list[i].url + separator
187
      }
188
      return strs != "" ? strs.substr(0, strs.length - 1) : ""
189 190 191
    },
    checkFileIsImage(filePath) {
      const fileExtension = filePath.slice(filePath.lastIndexOf(".") + 1).toLowerCase()
192
      const fileTypes = ["png", "jpg", "jpeg", "gif"]
193 194 195 196 197
      if (fileTypes.includes(fileExtension)) {
        return true
      }
      return false
    }
198 199
  }
}
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
</script>

<style scoped lang="scss">
.upload-file-uploader {
  margin-bottom: 5px;
}
.upload-file-list .el-upload-list__item {
  border: 1px solid #e4e7ed;
  line-height: 2;
  margin-bottom: 10px;
  position: relative;
}
.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
}
.ele-upload-list__item-content-action .el-link {
  margin-right: 10px;
}
221 222 223 224
.imgItem {
  display: flex;
  align-items: center;
}
225
</style>