wente
2023-11-20 819468f088be66befd788d357af44a496150d36e
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
<template>
  <div class="zt-upload">
    <!-- 文件上传 -->
    <el-upload
      ref="upload"
      class="upload-input"
      :class="{hide: uploadDisabled || !isShowUpload}"
      :accept="accept"
      :action="uploadAction"
      :before-upload="handleBeforeUpload"
      :data="data"
      :disabled="uploading"
      :drag="false"
      :limit="limit"
      list-type="text"
      :multiple="multiple"
      :name="name"
      :on-change="handleChange"
      :on-error="handleUploadError"
      :on-exceed="handleExceed"
      :on-success="handleUploadSuccess"
      :on-progress="onUploadProgress"
      :show-file-list="false"
      :file-list="fileList"
      v-if="!image && !crop"
 
    >
      <el-button class="upload-btn" size="mini" type="primary" icon="el-icon-upload"
                 v-show="!uploadDisabled && isShowUpload">{{ buttonText }}
      </el-button>
      <div slot="tip" class="el-upload__tip" v-show="!uploadDisabled && isShowUpload && tip">{{ tip }}</div>
    </el-upload>
 
    <div v-show="progressFlag">
    <el-progress :text-inside="true" :stroke-width="30" :percentage="progressPercent" :format="format"></el-progress>
 
</div>
 
    <ul class="el-upload-list el-upload-list--text" v-if="!image && !crop && showFileList">
      <li tabindex="0" class="el-upload-list__item is-success" v-for="(file, index) in uploadList" :key="file.id">
        <a class="el-upload-list__item-name" :href="file.url" target="_blank"><i
          class="el-icon-document"></i>{{ file.name }}</a>
        <label class="el-upload-list__item-status-label">
          <i class="el-icon-upload-success el-icon-circle-check"></i>
        </label>
        <i class="el-icon-close" @click.stop="handleRemove(index)" v-show="!uploadDisabled"></i>
      </li>
    </ul>
 
    <!-- 图片列表 -->
    <ele-gallery
      :lazy="lazy"
      :remove-fn="handleRemove"
      :size="size"
      :sliceSingle="true"
      :source="galleryValues"
      :thumbSuffix="thumbSuffix"
      :title="title"
      v-if="image && !crop"
    >
      <template slot="uploader">
        <!-- 上传组件 -->
        <el-upload
          ref="upload"
          :accept="accept"
          :action="uploadAction"
          :before-upload="handleBeforeUpload"
          :data="data"
          :disabled="uploading"
          :drag="Boolean(drag)"
          :limit="limit"
          :list-type="drag ? 'picture' : 'picture-card'"
          :multiple="multiple"
          :on-change="handleChange"
          :on-error="handleUploadError"
          :on-exceed="handleExceed"
          :on-success="handleUploadSuccess"
          :show-file-list="false"
          :file-list="fileList"
          v-show="!uploadDisabled && isShowUpload"
        >
          <div v-loading="uploading">
            <!-- drag显示 -->
            <template v-if="drag">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">
                将文件拖到此处,或
                <em>点击上传</em>
              </div>
            </template>
 
            <!-- 非drag -->
            <template v-else>
              <div :style="{ width: size + 'px', height: size + 'px', lineHeight: size + 'px' }">
                <i class="el-icon-plus"></i>
              </div>
            </template>
          </div>
 
          <!-- 公共 -->
          <div
            class="el-upload__tip"
            slot="tip"
            v-if="showTip"
          >
            请上传
            <b style="color: #F56C6C">{{ fileType.length ? fileType.join('/') : '图片' }}</b>
            格式文件
            <template v-if="fileSize">
              ,且大小不超过
              <b style="color: #F56C6C">{{ fileSize }}MB</b>
            </template>
          </div>
        </el-upload>
      </template>
    </ele-gallery>
 
    <!-- 图片裁剪 -->
    <div v-if="crop">
      <div
        :style="{ width: size + 'px', height: size + 'px', lineHeight: size + 'px' }"
        @click="isShowCrop = true"
        class="el-upload el-upload--picture-card"
        style="margin-bottom: 20px;"
        v-show="!uploadDisabled && isShowUpload"
      >
        <i class="el-icon-plus avatar-uploader-icon"></i>
      </div>
 
      <cropper
        ref="cropper"
        :field="name"
        :width="cropWidth"
        :height="cropHeight"
        :noCircle="cropHeight !== cropWidth"
        :params="data"
        :url="uploadAction"
        @crop-success="handleCropSuccess"
        @crop-upload-fail="handleCropUploadError"
        @crop-upload-success="handleCropUploadSuccess"
        @src-file-set="handleSetFileSet"
        class="zt-upload-image--cropper"
        img-format="png"
        v-if="isShowCrop"
        v-model="isShowCrop"
      ></cropper>
 
      <ele-gallery
        :lazy="lazy"
        :remove-fn="handleRemove"
        :size="size"
        :sliceSingle="true"
        :source="galleryValues"
        :thumbSuffix="thumbSuffix"
        :title="title"
        :disabled="uploadDisabled"
        v-show="isShowGrllery"
      />
    </div>
  </div>
</template>
 
<script>
import Cookies from 'js-cookie'
import Cropper from 'vue-image-crop-upload'
import EleGallery from '../../vue-ele-gallery'
 
export default {
  name: 'ZtUploader',
  props: {
    // 值
    value: {
      type: [Object, Array],
      default() {
        return this.multiple ? [] : null
      }
    },
    action: {
      type: String,
      default: '/sys/oss/upload'
    },
    // 是否为图片
    image: {
      type: Boolean,
      default: false
    },
    // 是否剪裁
    crop: {
      type: Boolean,
      default: false
    },
    // 裁剪高度
    cropHeight: {
      type: Number
    },
    // 裁剪宽度
    cropWidth: {
      type: Number
    },
    // 是否启用拖拽上传
    drag: {
      type: Boolean,
      default: false
    },
    // 是否支持多选文件
    multiple: {
      type: Boolean,
      default: false
    },
    // 图片显示大小
    size: {
      type: Number,
      default: 100
    },
    // 大小限制(MB)
    fileSize: {
      type: Number
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => []
    },
    // 缩略图后缀, 例如七牛云缩略图样式 (?imageView2/1/w/20/h/20)
    thumbSuffix: {
      type: String,
      default: ''
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    },
    // 弹窗标题
    title: String,
    // 图片懒加载
    lazy: {
      type: Boolean,
      default: false
    },
    // 文件个数显示
    limit: {
      type: Number,
      default: 10
    },
    // 上传时附带的额外参数
    data: Object,
    // 上传的文件字段名
    name: {
      type: String,
      default: 'file'
    },
    // 接受上传的文件类型(thumbnail-mode 模式下此参数无效)
    accept: String,
    buttonText: {
      type: String,
      default: '上传'
    },
    tip: String,
    showFileList: {
      type: Boolean,
      default: true
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  components: {
    Cropper,
    EleGallery
  },
  inject: {
    elForm: {
      default: ''
    }
  },
  data() {
    return {
      progressPercent: 0,
      uploadAction: `${window.SITE_CONFIG['apiURL']}${this.action}?token=${Cookies.get('token')}`,
      cropData: {},
      isShowCrop: false,
      uploading: false,
      fileList: this.getUploadList(this.value),
      uploadList: this.getUploadList(this.value),
      progressFlag:false
    }
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType.length || this.fileSize)
    },
    galleryValues() {
      let urls = []
      if (this.value) {
        if (this.multiple) {
          this.value.forEach(v => urls.push({
            src: v.url,
            title: v.name
          }))
        } else {
          urls.push({
            src: this.value.url,
            title: this.value.name
          })
        }
      }
      return urls
    },
    isShowUpload() { // 是否显示上传按钮
      if (this.multiple) {
        return this.uploadList.length < this.limit
      } else {
        return this.uploadList.length === 0
      }
    },
    uploadDisabled() {
      return this.disabled || (this.elForm || {}).disabled
    },
    successFiles() {
      return this.uploadList.filter((file) => file.status === 'success')
    },
    isShowGrllery() {
      return this.galleryValues.length > 0
    }
  },
  watch: {
    value(val, oldval) {
      if (this.uploadList !== val) {
        this.uploadList = this.getUploadList(val)
        this.fileList = this.getUploadList(val)
        console.log(this.fileList,'this.fileList this.fileList')
        this.$emit('getUploaderImg',this.fileList)
      }
    },
    isShowCrop(value) {
      if (value === false) {
        this.cropData = {}
      }
    }
  },
  methods: {
    format(percentage) {
      return percentage === 100 ? '后台正在处理' : `${percentage}%`;
    },
    // 获取已上传的文件列表
    getUploadList(val) {
      if (val) {
        console.log(val, 'getUploadList val')
        if (!this.multiple) { // 单选
          return [val]
        } else {
          console.log([...val], 'getUploadList [...val]')
          return [...val]
        }
      } else {
        return []
      }
    },
    onUploadProgress(event, file, fileList) {
      this.progressFlag = true
      let per = Number(
        ((event.loaded / event.total) * 100).toFixed(2)
      )
      this.progressPercent = per > 100 ? 100 : per
    },
    handleSetFileSet(fileName, fileType, fileSize) {
      const uid = this.cropData.uid || new Date().getTime()
      this.cropData = {
        name: fileName,
        percentage: 0,
        size: fileSize,
        type: fileType,
        status: 'ready',
        uid: uid
      }
    },
    handleCropSuccess(b64Data) {
      this.cropData.url = b64Data
    },
    handleCropUploadError(status) {
      this.$message.error('上传失败, 请重试')
      this.$emit('error', status)
    },
    handleCropUploadSuccess(response) {
      this.cropData.status = 'success'
      this.cropData.percentage = 100
      this.cropData.response = response
      const file = Object.assign({}, this.cropData)
      this.handleUploadSuccess(response, file)
    },
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      let isAccept = true
      if (this.fileType.length) { // 文件类型(后缀)一致
        let fileExtension = ''
        if (file.name.lastIndexOf('.') > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1)
        }
        isAccept = this.fileType.some((type) => {
          if (file.type.indexOf(type) > -1) return true
          if (fileExtension && fileExtension.indexOf(type) > -1) return true
          return false
        })
      }
      if (!isAccept) {
        this.$message.error(`文件格式不正确, 请上传${this.fileType.join('/')}格式文件!`)
        return false
      }
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize
        if (!isLt) {
          this.$message.error(`上传大小不能超过 ${this.fileSize} MB!`)
          return false
        }
      }
      this.uploading = true
      return true
    },
    handleChange() {
      this.uploading = false
      /*const config = {
        onUploadProgress: (progressEvent) => {
          this.progressPercent = Number(
            ((progressEvent.loaded / progressEvent.total) * 90).toFixed(2)
          )
        }
      }
      //this.progressFlag = true;
      let form = new FormData();
      form.append("file", params.file);
      this.$http.post( this.uploadAction,form,config ).then((res) => {
        this.progressPercent = 100;
      })*/
    },
    // 文件个数超出
    handleExceed() {
      this.$message.error(`最多上传${this.limit}个`)
    },
    // 上传失败
    handleUploadError(err) {
      this.uploading = false
      this.$message.error('上传失败, 请重试')
      this.$emit('error', err)
    },
    // 上传成功回调
    handleUploadSuccess(response, file) {
      console.log(response, file,'response, file')
      if (response.code === 0) {
        this.progressPercent = 100
        this.uploading = false
        // this.$message.success('上传成功')
        if (this.multiple) {
          this.uploadList.push(response.data)
          this.$emit('input', this.uploadList)
        } else {
          this.$emit('input', response.data)
        }
        this.progressFlag = false
        this.progressPercent = 0
      }
    },
    async handleRemove(index) {
      let file = this.uploadList[index]
      if (file.status === 1) { // 证书文件,直接从列表删除,不保存数据库
        this.handRemoveAndSetValue(index)
      } else {
        if (await this.$tip.confirm(this.$t('prompt.info', {'handle': this.$t('delete')}))) {
          let res = await this.$http.delete('/sys/oss', {'data': [file.id]})
          if (res.success) {
            await this.$tip.success()
            this.handRemoveAndSetValue(index)
          }
        }
      }
    },
    handRemoveAndSetValue(index) {
      if (this.multiple) {
        this.uploadList.splice(index, 1)
        this.$refs.upload.uploadFiles.splice(index, 1)
        this.$emit('input', this.uploadList || [])
      } else {
        this.$emit('input', null)
      }
    }
  },
  mounted() {
    // 插入到body中, 避免弹出层被遮盖
    if (this.crop && this.$refs.cropper) {
      document.body.appendChild(this.$refs.cropper.$el)
    }
  }
}
</script>
 
<style>
.zt-upload {
  line-height: 1;
}
 
.zt .upload-input .upload-btn {
  padding: 8px 12px;
}
 
.zt .upload-input.hide {
  height: 0px;
}
 
.zt-upload .el-loading-spinner {
  line-height: 1;
}
 
.zt-upload .el-icon-plus {
  vertical-align: middle;
}
 
.zt-upload .el-upload--picture-card {
  width: auto;
  height: auto;
  background: none;
  line-height: inherit;
}
 
/* 裁剪 */
.vue-image-crop-upload.zt-upload-image--cropper {
  z-index: 99;
}
 
.zt-upload-image--cropper .vicp-drop-area {
  background-color: #fbfdff !important;
}
 
.zt-upload-image--cropper .vicp-icon1-arrow {
  border-bottom-color: #909399 !important;
}
 
.zt-upload-image--cropper .vicp-icon1-body {
  background-color: #909399 !important;
}
 
.zt-upload-image--cropper .vicp-icon1-bottom {
  border-color: #909399 !important;
}
</style>