gaoluyang
14 小时以前 100f14bad7a37a30ccdea6b388e9bc6e7de0f2e2
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
<script lang="ts" setup>
import type { UploadFile, UploadProps } from 'ant-design-vue';
import type { UploadRequestOption } from 'ant-design-vue/lib/vc-upload/interface';
 
import type { FileUploadProps } from './typing';
 
import type { AxiosProgressEvent } from '#/api/infra/file';
 
import { computed, ref, toRefs, watch } from 'vue';
 
import { IconifyIcon } from '@vben/icons';
import { $t } from '@vben/locales';
import { checkFileType, isFunction, isObject, isString } from '@vben/utils';
 
import { Button, message, Upload } from 'ant-design-vue';
 
import { UploadResultStatus } from './typing';
import { useUpload, useUploadType } from './use-upload';
 
defineOptions({ name: 'FileUpload', inheritAttrs: false });
 
const props = withDefaults(defineProps<FileUploadProps>(), {
  value: () => [],
  modelValue: undefined,
  directory: undefined,
  disabled: false,
  drag: false,
  helpText: '',
  maxSize: 2,
  maxNumber: 1,
  accept: () => [],
  multiple: false,
  api: undefined,
  resultField: '',
  returnText: false,
  showDescription: false,
  showDownloadIcon: true,
  valueKey: 'url',
  valuePrefix: '',
});
const emit = defineEmits([
  'change',
  'update:value',
  'update:modelValue',
  'delete',
  'returnText',
  'preview',
]);
const { accept, helpText, maxNumber, maxSize } = toRefs(props);
const isInnerOperate = ref<boolean>(false);
const { getStringAccept } = useUploadType({
  acceptRef: accept,
  helpTextRef: helpText,
  maxNumberRef: maxNumber,
  maxSizeRef: maxSize,
});
 
const currentValue = computed(() => {
  return props.modelValue === undefined ? props.value : props.modelValue;
});
 
const isUsingModelValue = computed(() => {
  return props.modelValue !== undefined;
});
 
const fileList = ref<UploadProps['fileList']>([]);
const isLtMsg = ref<boolean>(true);
const isActMsg = ref<boolean>(true);
const isFirstRender = ref<boolean>(true);
const uploadNumber = ref<number>(0);
const uploadList = ref<any[]>([]);
 
watch(
  currentValue,
  (v) => {
    if (isInnerOperate.value) {
      isInnerOperate.value = false;
      return;
    }
    let value: string[] = [];
    if (v) {
      if (Array.isArray(v)) {
        value = v;
      } else {
        value.push(v);
      }
      const existingMap = new Map<string | number, UploadFile>();
      for (const f of fileList.value ?? []) {
        const id = (f as any)?.response?.[props.valueKey] ?? (f as any)?.[props.valueKey] ?? f?.uid;
        if (id != null) existingMap.set(id, f);
      }
      fileList.value = value
        .map((item, i) => {
          if (item && isString(item)) {
            return existingMap.get(item) ?? {
              uid: `${-i}`,
              name: item.slice(Math.max(0, item.lastIndexOf('/') + 1)),
              status: UploadResultStatus.DONE,
              url: item,
            };
          } else if (item && isObject(item)) {
            const key = item[props.valueKey] ?? item.uid;
            return (key != null && existingMap.get(key)) || { ...item, url: String((item as any).url ?? '') };
          } else if (item && (typeof item === 'number' || typeof item === 'string')) {
            return existingMap.get(item) ?? {
              uid: `${-i}`,
              name: `文件 ${String(item)}`,
              status: UploadResultStatus.DONE,
              url: String(item),
              response: { [props.valueKey]: item },
            } as UploadFile;
          }
          return null;
        })
        .filter(Boolean) as UploadProps['fileList'];
    }
    if (!isFirstRender.value) {
      emit('change', value);
      isFirstRender.value = false;
    }
  },
  {
    immediate: true,
    deep: true,
  },
);
 
/** 处理文件删除 */
async function handleRemove(file: UploadFile) {
  if (fileList.value) {
    const index = fileList.value.findIndex((item) => item.uid === file.uid);
    index !== -1 && fileList.value.splice(index, 1);
    const value = getValue();
    isInnerOperate.value = true;
    emit('update:value', value);
    emit('update:modelValue', value);
    emit('change', value);
    emit('delete', file);
  }
}
 
/** 处理文件预览 */
function handlePreview(file: UploadFile) {
  emit('preview', file);
}
 
/** 处理文件数量超限 */
function handleExceed() {
  message.error($t('ui.upload.maxNumber', [maxNumber.value]));
}
 
/** 处理上传错误 */
function handleUploadError(error: any) {
  console.error('上传错误:', error);
  message.error($t('ui.upload.uploadError'));
  uploadNumber.value = Math.max(0, uploadNumber.value - 1);
}
 
async function beforeUpload(file: File) {
  if (fileList.value!.length >= props.maxNumber) {
    message.error($t('ui.upload.maxNumber', [props.maxNumber]));
    return Upload.LIST_IGNORE;
  }
 
  const { maxSize, accept } = props;
  const isAct = checkFileType(file, accept);
  if (!isAct) {
    message.error($t('ui.upload.acceptUpload', [accept]));
    isActMsg.value = false;
    setTimeout(() => (isActMsg.value = true), 1000);
    return Upload.LIST_IGNORE;
  }
  const isLt = file.size / 1024 / 1024 > maxSize;
  if (isLt) {
    message.error($t('ui.upload.maxSizeMultiple', [maxSize]));
    isLtMsg.value = false;
    setTimeout(() => (isLtMsg.value = true), 1000);
    return Upload.LIST_IGNORE;
  }
 
  uploadNumber.value++;
  if (props.returnText) {
    const fileContent = await file.text();
    emit('returnText', fileContent);
  }
  return true;
}
 
async function customRequest(info: UploadRequestOption) {
  let { api } = props;
  if (!api || !isFunction(api)) {
    api = useUpload(props.directory).httpRequest;
  }
  try {
    const progressEvent: AxiosProgressEvent = (e) => {
      const percent = Math.trunc((e.loaded / e.total!) * 100);
      info.onProgress!({ percent });
    };
    const res = await api?.(info.file as File, progressEvent);
    handleUploadSuccess(res, info.file as File);
    info.onSuccess!(res);
    message.success($t('ui.upload.uploadSuccess'));
  } catch (error: any) {
    console.error(error);
    info.onError!(error);
    handleUploadError(error);
  }
}
 
function handleUploadSuccess(res: any, file: File) {
  const index = fileList.value?.findIndex((item) => item.name === file.name);
  if (index !== -1) {
    fileList.value?.splice(index!, 1);
  }
 
  const fileUrl = res?.url || res?.data || (typeof res === 'string' ? res : '');
  uploadList.value.push({
    name: res?.name || file.name,
    url: fileUrl,
    id: res?.id,
    response: res,
    status: UploadResultStatus.DONE,
    uid: file.name + Date.now(),
  });
 
  if (uploadList.value.length >= uploadNumber.value) {
    fileList.value?.push(...uploadList.value);
    uploadList.value = [];
    uploadNumber.value = 0;
 
    const value = getValue();
    isInnerOperate.value = true;
    emit('update:value', value);
    emit('update:modelValue', value);
    emit('change', value);
  }
}
 
function getValue() {
  const list = (fileList.value || [])
    .filter((item) => item?.status === UploadResultStatus.DONE)
    .map((item: any) => {
      if (item?.response && props?.resultField) {
        return item?.response;
      }
      const val =
        item?.response?.[props.valueKey] ??
        item?.[props.valueKey] ??
        item?.url ??
        item?.response?.url ??
        item?.response;
      return props.valuePrefix ? `${props.valuePrefix}${val}` : val;
    });
 
  if (props.maxNumber === 1) {
    const singleValue = list.length > 0 ? list[0] : '';
    if (
      isString(props.value) ||
      (isUsingModelValue.value && isString(props.modelValue))
    ) {
      return singleValue;
    }
    return singleValue;
  }
 
  if (isUsingModelValue.value) {
    return Array.isArray(props.modelValue) ? list : list.join(',');
  }
 
  return Array.isArray(props.value) ? list : list.join(',');
}
</script>
 
<template>
  <div>
    <Upload
      v-bind="$attrs"
      v-model:file-list="fileList"
      :accept="getStringAccept"
      :before-upload="beforeUpload"
      :custom-request="customRequest"
      :disabled="disabled"
      :max-count="maxNumber"
      :multiple="multiple"
      list-type="text"
      :progress="{ showInfo: true }"
      :show-upload-list="{
        showPreviewIcon: true,
        showRemoveIcon: true,
        showDownloadIcon,
      }"
      @remove="handleRemove"
      @preview="handlePreview"
      @reject="handleExceed"
    >
      <div v-if="drag" class="upload-drag-area">
        <p class="ant-upload-drag-icon">
          <IconifyIcon icon="lucide:cloud-upload" />
        </p>
        <p class="ant-upload-text">点击或拖拽文件到此区域上传</p>
        <p class="ant-upload-hint">
          支持{{ accept.join('/') }}格式文件,不超过{{ maxSize }}MB
        </p>
      </div>
      <div v-else-if="fileList && fileList.length < maxNumber">
        <Button>
          <IconifyIcon icon="lucide:cloud-upload" />
          {{ $t('ui.upload.upload') }}
        </Button>
      </div>
      <div
        v-if="showDescription && !drag"
        class="mt-2 flex flex-wrap items-center"
      >
        请上传不超过
        <div class="mx-1 font-bold text-primary">{{ maxSize }}MB</div>
        的
        <div class="mx-1 font-bold text-primary">{{ accept.join('/') }}</div>
        格式文件
      </div>
    </Upload>
  </div>
</template>
 
<style scoped>
.upload-drag-area {
  padding: 20px;
  text-align: center;
  background-color: #fafafa;
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  transition: border-color 0.3s;
}
 
.upload-drag-area:hover {
  border-color: #1890ff;
}
 
.ant-upload-drag-icon {
  margin-bottom: 16px;
  font-size: 48px;
  color: #d9d9d9;
}
 
.ant-upload-text {
  margin-bottom: 8px;
  font-size: 16px;
  color: #666;
}
 
.ant-upload-hint {
  font-size: 14px;
  color: #999;
}
</style>
 
<style>
.ant-upload-list-text .ant-upload-list-item {
  cursor: pointer;
}
</style>