seatonwan9
2025-08-14 a0fc5b1e703769a8936fd8671ec9cdd9adfda20a
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
<template>
  <div class="upload">
    <!-- 上传组件封装 -->
    <el-upload
      ref="uploadRef"
      :file-list="fileList"
      :accept="acceptType"
      action="#"
      :limit="limit"
      :multiple="multiple"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :on-exceed="handleExceed"
      :http-request="uplodFile"
      :before-upload="handleBeforeUpload"
    >
      <slot>
        <el-button type="primary" :loading="fileLoading">选择文件</el-button>
      </slot>
      <template #tip>
        <div class="el-upload__tip">{{ tips }}</div>
      </template>
    </el-upload>
  </div>
</template>
 
<script setup lang="ts">
import type { UploadProps } from 'element-plus'
import { genFileId, UploadRawFile } from 'element-plus'
 
import createAxios from '@/utils/axios'
 
interface Props {
  tips?: string
  multiple?: boolean
  fileList: any
  acceptType?: string
  size?:number
  limit?: number
}
 
const props = withDefaults(defineProps<Props>(), {
  tips: '只能上传.zip .rar .exe格式文件,并且只能上传一个文件',
  multiple: true,
  acceptType: '.zip,.rar,.exe',
  fileList: [],
  size:500,
  limit: 9,
})
const fileLists = ref<any>()
const fileList = ref<any>([])
const emit = defineEmits(['update:fileIds', 'beginUpload', 'removeFile'])
const uploadRef = ref()
 
// watch(
//   () => props.fileList,
//   (newVal: any) => {
//     if (props.fileList.length > 0) {
//       props.fileList.forEach((item: any) => {
//         fileIdList.value.push({
//           fileId: item.fileId,
//           uid: item.uid,
//         })
//       })
//     }
//   },
//   {
//     immediate: true,
//   }
// )
// 点击预览上传的文件
const handlePreview: UploadProps['onPreview'] = (file: any) => {
  console.log('预览已经上传的文件', file)
}
const handleBeforeUpload = (file: File): boolean => {
  const isLt3M = file.size / 1024 / 1024 < props.size;
  if (!isLt3M) {
   ElMessage.error(`每个文件的大小不能超过${props.size}MB!`)
   return false;
  }
  return true;
 };
// 移除已经上传的文件
const handleRemove: UploadProps['onRemove'] = (file: any, uploadFiles) => {
  // console.log('移除已经上传的文件 file', file)
  // console.log('前fileIdList.value', fileIdList.value)
  fileList.value.map((item: any) => {
    if (item.fileId === file?.fileId || item.uid == file?.uid) {
      fileList.value.splice(fileList.value.indexOf(item), 1)
    }
  })
  let ids = fileList.value.map((item: any) => {
    return item.fileId
  })
  emit('update:fileIds', ids)
}
// 问价移除前的操作
const beforeRemove: UploadProps['beforeRemove'] = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(` 是否删除${uploadFile.name} ?`).then(
    () => true,
    () => false
  )
}
// 文件超出限制提示
const handleExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
  uploadRef.value?.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  uploadRef.value?.handleStart(file)
  uploadRef.value!.submit()
}
const fileLoading = ref<boolean>(false)
// 自定义上传文件
const uplodFile = (option: any, options: any) => {
  let param = new FormData()
  param.append('file', option.file)
  fileLoading.value = true
  emit('beginUpload')
  return new Promise((resolve, reject) => {
    // 调用上传文件方法
    createAxios({
      url: '/admin/common/fileUpload',
      headers: {
        'Content-Type': 'multipart/form-data',
      },
      data: param,
      onUploadProgress: (progressEvent) => {
        const complete = parseInt(
          ((progressEvent.loaded / progressEvent.total) * 100) | 0,
          10
        )
        // 重点二:onProgress()方法需要以上方接收的形参来调用
        // 这个方法有一个参数"percent",给他进度值 complete 即可
        option.onProgress({ percent: complete })
      },
    })
      .then((res:any) => {
        if (res.code == 200) {
          ElMessage.success('文件上传成功!')
          fileList.value.push({
            fileId: res.data.fileId,
            uid: option.file.uid,
          })
          let ids = fileList.value.map((item: any) => {
            return item.fileId
          })
          emit('update:fileIds', ids)
          resolve(res.msg)
        } else {
          console.log('fileIdList',  fileList)
          ElMessage.warning('只能上传视频(MP4)、图片、pdf、docx、exe、rar、zip格式的文件')
        }
      })
      .finally(() => {
        fileLoading.value = false
      })
  })
}
  // 获取到图片
  const getFileUrlFun = (data?: any) => {
    fileList.value=[...data]
  }
  
const clearUploadFile = () => {
    fileList.value=[]
    emit('update:fileIds', [])
  }
defineExpose({clearUploadFile,getFileUrlFun})
</script>
 
<style scoped lang="scss">
.el-upload__tip {
  color: #d9001b;
}
</style>