fuliqi
2024-01-24 29c1e7eb5ac16e90d8991a86c1c071bc312ec8d9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
<template>
  <div>
    <el-upload class="upload-demo" action="api" :show-file-list="false" multiple :headers="headers"
               :accept="accept" :http-request="handleRequrst" :on-change="handleChange"
               v-customLoading="{isLoading:isLoading,percentage:percentage}" :auto-upload="false">
      <div class="file_item" v-for="item in fileList" :key="item.id">
        {{item.fileName}}
        <span class="file_delete" @click="handleRemove(item)">×</span>
      </div>
      <el-button size="mini" slot="trigger" type="primary">点击上传</el-button>
      <div slot="tip" class="itemTip">
        <slot></slot>
      </div>
    </el-upload>
  </div>
</template>
 
<script>
import {
  getUuid
} from '@/api/sm'
import uploadFile from '@/api/uploadFile'
import { mapState } from 'vuex'
 
export default {
  props: {
    // 限制文件上传个数
    limitNumber: {
      type: Number,
      default: 1
    },
    fileList: {
      type: Array,
      default: function() {
        return []
      }
    },
    accept: {
      type: String,
      default: '.jpg,.jpeg,.png,.JPG,.JPEG,.PBG'
    },
    // 图片接收类型
    uploadPath: {
      type: String,
      default: 'product'
    },
    isShow: {
      type: Boolean,
      default: false
    },
    reload: {
      type: Boolean,
      default: false
    },
    customTips: {
      type: String,
      default: ''
    }
  },
  computed: {
    ...mapState(['token', 'token_type']),
    headers() {
      return {
        Authorization: `Bearer ${this.token}`,
        'Content-Type': 'application/json'
      }
    }
  },
  data() {
    return {
      count: 0,
      files: [],
      businessId: null,
      percentage: null, // 进度条数值
      isLoading: false// 是否展示进度条遮罩
    }
  },
  created() {
    this.businessId = getUuid().split('-').join('')
  },
  watch: {
    count(newValue, oldValue) {
      if (newValue !== this.files.length) {
        this.handleRequrst()
      }
    },
    /**
     * 监听页面变化 --- 弹窗的情况下
     */
    isShow: {
      immediate: true, // immediate选项可以开启首次赋值监听
      async handler(newVal, oldVal) {
        if (newVal) {
          this.updateBusinessId();
        }
      },
    },
    reload: {
      immediate: true, // immediate选项可以开启首次赋值监听
      async handler(newVal, oldVal) {
        if (newVal) {
          this.updateBusinessId();
        }
      },
    }
  },
  methods: {
    // 当文件改变时获取选中的文件
    handleChange(file, fileList) {
      if (!this.beforeAvatarUpload(file)) return // 限制图片上传
      this.files.push(file.raw)
      this.count = fileList.length
      this.count++
    },
    // 更新ID
    updateBusinessId() {
      this.businessId = getUuid().split('-').join('')
    },
    /**
   *上传图片
    */
    async handleRequrst(param) {
      if (this.files.length + this.fileList.length > this.limitNumber) {
        if (!this.customTips || this.customTips === '') {
          this.$message.warning(`当前限制选择 ${this.limitNumber} 个文件,本次选择了 ${this.files.length} 个文件,请重新选择`)
        } else {
          this.$message.warning(this.customTips);
        }
        this.files = []
        return
      }
      const formData = new FormData()
      this.files.forEach(item => {
        formData.append('files', item)
      })
      formData.append('bizCode', this.businessId)
      formData.append('path', this.uploadPath)
      // 进度条配置
      const config = {
        onUploadProgress: ProgressEvent => {
          const progressPercent = Math.round(ProgressEvent.loaded / ProgressEvent.total * 100 | 0)
          this.percentage = progressPercent === 100 ? 99 : progressPercent
          this.isLoading = true
        }
      }
      try {
        const res = await uploadFile.fileUpload(formData, config)
        if (res.data instanceof Array) {
          // res.data.forEach(item => {
          //   var param = {
          //     url: item.like,
          //     id: item.key,
          //     businessId: item.bizCode,
          //     alias: this.getFileName(item.like)
          //   }
          //   this.$emit('handle-success', param)
          // })
          this.getFileInfo(this.businessId) // 查询上传的文件
          this.files = []
          this.percentage = 100
          this.isLoading = false
        } else {
          this.isLoading = false
          this.files = []
        }
      } catch (error) {
        this.$message.error('上传文件失败!请重新上传')
        this.files = []
        this.isLoading = false
      }
    },
    /**
     * 获取文件信息
     */
    getFileInfo(businessId) {
      uploadFile.findFileInfoByBusinessId(businessId).then(res => {
        if (res.code === '200') {
          if (res.data) {
            const arr = []
            res.data.forEach(item => {
              if (!item.isDelete) {
                arr.push({
                  url: item.fileInfo.like,
                  id: item.key,
                  businessId: item.bizCode,
                  fileName: item.oriFileName
                })
              }
            })
            this.$emit('handle-success', arr, this.businessId)
          }
        }
      })
    },
    getFileName(path) {
      var pos = path.lastIndexOf('/')
      return path.substring(pos + 1)
    },
    handleRemove(file) {
      this.$emit('handle-remove', file)
    },
    handleExceed(files, fileList) {
    },
    beforeAvatarUpload(file) {
      var nameType = file.name.substring(file.name.lastIndexOf('.') + 1)
      var fileSize = file.size / 1024 / 1024 < 300
      var fileType = this.accept.toLowerCase().includes(nameType.toLowerCase())
      const imgSize = file.raw.type.includes('image')
      if (imgSize) {
        const fileSize = file.size / 1024 / 1024 < 5
        if (!fileSize) {
          this.$message.error('上传失败!图片大小不能超多 5MB!请重新上传')
          return false
        }
      }
      if (!fileSize) {
        this.$message.error('上传失败!上传文件大小不能超过 300MB!请重新上传')
        return false
      }
      if (!fileType) {
        this.$message.error(`上传失败!仅支持${this.accept}格式,请重新上传`)
        return false
      }
      return true
    }
  }
}
</script>
 
<style lang="scss">
.file_item {
  cursor: pointer;
  padding: 0 8px;
  .file_delete {
    content: "×";
    float: right;
    color: #606266;
    opacity: 0.75;
    font-size: 16px;
  }
  &:hover {
    color: #409eff;
    background: #eeeeee;
    opacity: 0.75;
  }
}
</style>