index.tsx
20.5 KB
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
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
/*
* @Date: 2021-01-05 14:24:23
* @LastEditors: wangqiang@feewee.cn
* @LastEditTime: 2023-02-11 16:54:22
*/
import React, { useEffect, useRef, useState } from "react";
import { message, Popover, Spin, Upload } from "antd";
import {
LinkOutlined,
EyeOutlined,
DeleteOutlined,
FileTwoTone,
LoadingOutlined,
} from "@ant-design/icons";
import { UploadProps } from "antd/lib/upload";
import {
RcFile,
UploadChangeParam,
UploadFile,
} from "antd/lib/upload/interface";
import getFidFile, { FeeweeFileAccept } from "@/utils/getFidFile";
import COS from "@/utils/COS";
import {
getFileListDetailApi,
confirmThirdFileApi,
deleteFileApi,
} from "./api";
import "./index.less";
import { IMGURL } from "@/utils";
// @ts-ignore
interface Props extends UploadProps {
/**
* @description: 附件fid列表。
* @description: 如果在表单中使用,则需要再Form.Item 中声明valuePropName="fidList"
*/
fidList?: string[];
onChange?: (fidList: string[]) => void;
/** 使用腾讯云对象存储 */
useCos?: boolean;
/** 上传腾讯云-前缀文件夹名称 */
catalog?: string;
/** 不允许修改文件项列表 fid 数组[] */
freezeItems?: string[];
limitSize?: number; // 限制文件大小
limitUnit?: "kb" | "mb" | "KB" | "MB"; // 限制大小单位, 默认MB
children?: React.ReactNode;
}
/**
* @description: 自定义封装的 FeeweeUploadAttachment 上传附件组件
* @description: 使用方式:
* 1. 仅需要 传入 fidList 和 onChange 参数就可以使用基本用法;
* 2. 其他的参数同 Upload 组件的参数
* 3. useCos catalog freezeItems 同 APP 组件作用一样;
* 4. limitSize 和 limitUnit 是为了限制上传附件的大小
* @param {Props} props
*/
export default function FeeweeUploadAttachment({
useCos,
catalog = "",
limitSize = undefined,
limitUnit = "MB",
children,
freezeItems = [],
fidList,
onChange,
...props
}: Props) {
const [loading, setLoading] = useState(false);
const [fileList, setFileList] = useState<UploadFile[]>([]);
const removingFileFidList = useRef<string[]>([]);
useEffect(() => {
if (fidList?.length) {
setLoading(true);
// const hide = message.loading("", 0);
getFileListDetailApi(fidList)
.then((res) => {
setFileList(
(res.data || []).map((item) => ({
name: item.aliasName || item.fileName || "",
uid: item.fid || "",
url: item.fileUri,
status: "done",
size: item.length,
type: item.contentType,
response: { data: item.fileUri, fid: item.fid },
}))
);
})
.catch((error: any) => { })
.finally(() => {
// hide();
setLoading(false);
});
}
}, [fidList]);
if (!props.listType) {
props.listType = "text";
}
if (useCos) {
props.customRequest = (data) => COS.cosUpload({ ...data, uploadPath: "fw_fds_file/" + catalog });
} else {
props.action = "api/file/upload";
}
const onPreview = (file: UploadFile) => {
if (props.onPreview) {
props.onPreview(file);
return;
}
getFidFile(file?.response.data);
};
const beforeUpload = (file: RcFile, filelist: RcFile[]) => {
if (limitSize !== undefined && typeof limitSize === "number") {
const limit = isExceededSize(file, limitSize, limitUnit);
if (limit.success) {
return true;
} else {
message.error(limit.msg);
// @ts-ignore
file.status = "size_limit";
// @ts-ignore
file.errMsg = limit.msg;
return false;
}
}
return props.beforeUpload ? props.beforeUpload(file, filelist) : true;
};
const allFileDone = (fileList: UploadFile<any>[]) => (fileList || []).every((file) => file?.status !== "uploading");
const onUploadChange = async ({
file,
fileList,
}: UploadChangeParam<UploadFile>) => {
setFileList(
fileList.map((_file) => ({
..._file,
// @ts-ignore
status: _file?.status === "size_limit" ? "error" : _file?.status,
}))
);
if (file?.status === "done") {
if (useCos) {
try {
const ext_array = file?.name.split(".");
const { data } = await confirmThirdFileApi({
fileName: file?.name,
ext: "." + ext_array[ext_array.length - 1],
contentType: file?.type,
fileUri: file?.response.data,
length: file?.size,
});
file.response.fid = data;
if (allFileDone(fileList)) {
onChange &&
onChange(
fileList
.filter(
(file) => file?.status === "done" && file?.response.fid
)
.map((file) => file?.response.fid)
);
}
} catch (error: any) {
message.error(error.message || "确认文件失败", 2);
}
} else {
file.response.fid = file?.response.data;
if (allFileDone(fileList)) {
onChange &&
onChange(
fileList
.filter((file) => file?.status === "done" && file?.response.fid)
.map((file) => file?.response.fid)
);
}
}
}
};
const onFileRemove = async (file: UploadFile) => {
if (removingFileFidList.current.includes(file?.response?.fid)) return false;
if (file.status === "error" || file?.status === "uploading") {
setFileList(fileList.filter((_file) => _file.uid !== file.uid));
return true;
}
const hide = message.loading("删除中...", 0);
try {
removingFileFidList.current.push(file?.response.fid);
setLoading(true);
// await deleteFileApi(file?.response.fid);
// if (useCos) {
// await deleteCOSFile(file?.response.data);
// }
onChange &&
onChange((fidList || []).filter((fid) => fid !== file?.response.fid));
return Promise.resolve();
} catch (error: any) {
message.error(error.message || "删除文件失败", 2);
return Promise.reject();
} finally {
removingFileFidList.current = removingFileFidList.current.filter(
(fid) => fid !== file?.response.fid
);
setLoading(false);
hide();
}
};
return (
<Spin spinning={loading}>
<Upload
accept={FeeweeFileAccept}
beforeUpload={beforeUpload}
{...props}
onPreview={onPreview}
fileList={fileList}
onChange={onUploadChange}
onRemove={onFileRemove}
itemRender={(originalNode, file, fileList, { remove }) => {
const DOM =
props.listType === "picture-card"
? ListTypeOfPictureCard
: props.listType === "picture"
? ListTypeOfPicture
: ListTypeOfText;
return (
<DOM
file={file}
freezeItems={freezeItems}
remove={remove}
disabled={props.disabled}
/>
);
// return (
// <div
// id="FeeweeUploadAttachment"
// className={
// freezeItems.includes(file?.response?.fid)
// ? "FeeweeUploadAttachment_hidden_delete_icon"
// : ""
// }
// >
// {/* @ts-ignore */}
// {originalNode}
// </div>
// );
}}
>
{props.disabled ? (
fileList.length ? null : (
<span style={{ color: "#999" }}>暂无附件</span>
)
) : (
children
)}
</Upload>
</Spin>
);
}
interface ItemRenderProps {
file: UploadFile;
freezeItems?: string[];
remove: () => void;
disabled?: boolean;
}
const ListTypeOfText = ({
file,
freezeItems = [],
remove,
disabled,
}: ItemRenderProps) => (
<div
id="FeeweeUploadAttachment"
className={
freezeItems.includes(file?.response?.fid)
? "FeeweeUploadAttachment_hidden_delete_icon"
: ""
}
>
<div
className={`ant-upload-list-item ant-upload-list-item-done ${file?.status === "error" ? "ant-upload-list-item-error" : ""
} ant-upload-list-item-list-type-text`}
>
<div className="ant-upload-list-item-info">
{file?.status === "uploading" ? (
<span className="ant-upload-span">
<div className="ant-upload-text-icon">
<LoadingOutlined />
</div>
<span
className="ant-upload-list-item-name"
title={`${file?.name}(${file?.size ? getFileSize(file?.size) : ""
})`}
>
{file?.name}({file?.size ? getFileSize(file?.size) : ""})
</span>
<span className="ant-upload-list-item-card-actions">
<button
title="删除文件"
type="button"
onClick={() => remove()}
className="ant-btn ant-btn-text ant-btn-sm ant-btn-icon-only ant-upload-list-item-card-actions-btn"
>
<DeleteOutlined />
</button>
</span>
</span>
) : (
<span className="ant-upload-span">
<div className="ant-upload-text-icon">
<LinkOutlined />
</div>
<a
target="_blank"
rel="noopener noreferrer"
className="ant-upload-list-item-name"
title={file?.name}
href={
file?.status === "error"
? undefined
: IMGURL.showImage(file?.response?.data)
}
>
{file?.name}({file?.size ? getFileSize(file?.size) : ""})
</a>
{/* @ts-ignore */}
{file?.status === "error" && file?.errMsg ? (
// @ts-ignore
<span>{file?.errMsg}</span>
) : null}
<span className="ant-upload-list-item-card-actions">
{!disabled ? (
<button
title="删除文件"
type="button"
onClick={() => remove()}
className="ant-btn ant-btn-text ant-btn-sm ant-btn-icon-only ant-upload-list-item-card-actions-btn"
>
<DeleteOutlined />
</button>
) : null}
</span>
</span>
)}
</div>
{file?.status === "uploading" ? (
<div className="ant-upload-list-item-progress">
<div className="ant-progress ant-progress-line ant-progress-status-normal ant-progress-default">
<div className="ant-progress-outer">
<div className="ant-progress-inner">
<div
className="ant-progress-bg"
style={{ width: `${file?.percent || 0}%`, height: 2 }}
/>
</div>
</div>
</div>
</div>
) : null}
</div>
</div>
);
const ListTypeOfPictureCard = ({
file,
freezeItems = [],
remove,
disabled,
}: ItemRenderProps) => (
<div
id="FeeweeUploadAttachment"
className={
freezeItems.includes(file?.response?.fid)
? "FeeweeUploadAttachment_hidden_delete_icon"
: ""
}
>
<Popover
placement="topLeft"
content={
<div>
<p>
文件信息:{file?.name}({file?.size ? getFileSize(file?.size) : ""})
</p>
{/* @ts-ignore */}
{file?.errMsg ? (
<p>
{/* @ts-ignore */}
错误原因:<span style={{ color: "#ff4d4f" }}>{file?.errMsg}</span>
</p>
) : null}
</div>
}
>
<div
className={`ant-upload-list-item ant-upload-list-item-done ${file?.status === "error" ? "ant-upload-list-item-error" : ""
} ant-upload-list-item-list-type-picture-card`}
>
<div className="ant-upload-list-item-info">
{file?.status === "uploading" ? (
<span className="ant-upload-span">
<div className="ant-upload-list-item-thumbnail">文件上传中</div>
<span className="ant-upload-list-item-name" title={file?.name}>
{file?.name}
</span>
</span>
) : (
<span className="ant-upload-span">
<a
className="ant-upload-list-item-thumbnail ant-upload-list-item-file"
href={
file?.status === "error"
? undefined
: IMGURL.showImage(file?.response?.data)
}
target="_blank"
rel="noopener noreferrer"
>
{file?.type?.includes("image") ? (
<img
src={IMGURL.showImage(
file?.thumbUrl || file?.response?.data
)}
alt={`${file?.name}(${file?.size ? getFileSize(file?.size) : ""
})`}
className="ant-upload-list-item-image"
/>
) : (
<FileTwoTone style={{ fontSize: 26 }} />
)}
</a>
<span
className="ant-upload-list-item-name"
style={{
display: file?.type?.includes("image") ? "none" : undefined,
}}
title={`${file?.name}(${file?.size ? getFileSize(file?.size) : ""
})`}
>
{file?.name}({file?.size ? getFileSize(file?.size) : ""})
</span>
</span>
)}
</div>
{file?.status === "uploading" ? (
<div className="ant-upload-list-item-progress">
<div className="ant-progress ant-progress-line ant-progress-status-normal ant-progress-default">
<div className="ant-progress-outer">
<div className="ant-progress-inner">
<div
className="ant-progress-bg"
style={{ width: `${file?.percent || 0}%`, height: 2 }}
/>
</div>
</div>
</div>
</div>
) : (
<span className="ant-upload-list-item-actions">
<a
target="_blank"
rel="noopener noreferrer"
title="预览文件"
href={
file?.status === "error"
? undefined
: IMGURL.showImage(file?.response?.data)
}
style={{ display: file?.status === "error" ? "none" : undefined }}
>
<EyeOutlined />
</a>
{!disabled ? (
<button
title="删除文件"
type="button"
onClick={() => remove()}
className="ant-btn ant-btn-text ant-btn-sm ant-btn-icon-only ant-upload-list-item-card-actions-btn"
>
<DeleteOutlined />
</button>
) : null}
</span>
)}
</div>
</Popover>
</div>
);
const ListTypeOfPicture = ({
file,
freezeItems = [],
remove,
disabled,
}: ItemRenderProps) => (
<div
id="FeeweeUploadAttachment"
className={
freezeItems.includes(file?.response?.fid)
? "FeeweeUploadAttachment_hidden_delete_icon"
: ""
}
>
<div
className={`ant-upload-list-item ant-upload-list-item-done ${file?.status === "error" ? "ant-upload-list-item-error" : ""
} ${file?.status === "uploading" ? "ant-upload-list-item-uploading" : ""
} ant-upload-list-item-list-type-picture`}
>
<div className="ant-upload-list-item-info">
{file?.status === "uploading" ? (
<span className="ant-upload-span">
<div className="ant-upload-list-item-thumbnail">
<LoadingOutlined />
</div>
<span
className="ant-upload-list-item-name"
title={`${file?.name}(${file?.size ? getFileSize(file?.size) : ""
})`}
>
{file?.name}({file?.size ? getFileSize(file?.size) : ""})
</span>
<span className="ant-upload-list-item-card-actions picture">
<button
title="删除文件"
type="button"
onClick={() => remove()}
className="ant-btn ant-btn-text ant-btn-sm ant-btn-icon-only ant-upload-list-item-card-actions-btn"
>
<DeleteOutlined />
</button>
</span>
</span>
) : (
<span className="ant-upload-span">
<a
className="ant-upload-list-item-thumbnail"
href={
file?.status === "error"
? undefined
: IMGURL.showImage(file?.response?.data)
}
target="_blank"
rel="noopener noreferrer"
>
{file?.type?.includes("image") ? (
<img
src={IMGURL.showImage(file?.thumbUrl || file?.response?.data)}
alt={`${file?.name}(${file?.size ? getFileSize(file?.size) : ""
})`}
className="ant-upload-list-item-image"
/>
) : (
<FileTwoTone style={{ fontSize: 26 }} />
)}
</a>
<a
target="_blank"
rel="noopener noreferrer"
className="ant-upload-list-item-name"
title={`${file?.name}(${file?.size ? getFileSize(file?.size) : ""
})`}
href={
file?.status === "error"
? undefined
: IMGURL.showImage(file?.response?.data)
}
>
{file?.name}({file?.size ? getFileSize(file?.size) : ""})
</a>
{/* @ts-ignore */}
{file?.status === "error" && file?.errMsg ? (
// @ts-ignore
<span>{file?.errMsg}</span>
) : null}
<span className="ant-upload-list-item-card-actions picture">
{!disabled ? (
<button
title="删除文件"
type="button"
onClick={() => remove()}
className="ant-btn ant-btn-text ant-btn-sm ant-btn-icon-only ant-upload-list-item-card-actions-btn"
>
<DeleteOutlined />
</button>
) : null}
</span>
</span>
)}
</div>
{file?.status === "uploading" ? (
<div className="ant-upload-list-item-progress">
<div className="ant-progress ant-progress-line ant-progress-status-normal ant-progress-default">
<div className="ant-progress-outer">
<div className="ant-progress-inner">
<div
className="ant-progress-bg"
style={{ width: `${file?.percent || 0}%`, height: 2 }}
/>
</div>
</div>
</div>
</div>
) : null}
</div>
</div>
);
const deleteCOSFile = (filePath: string) => {
return new Promise((resolve, reject) => {
COS.cosDelete({ filePath }, resolve, reject);
});
};
/**
* @description: 计算限制大小,统一返回限制大小转换为KB
* @param {number} limitSize
* @param {'kb' | 'mb' | 'KB' | 'MB'} limitUnit
* @return {number}
*/
function getLimitSize(
limitSize: number,
limitUnit: "kb" | "mb" | "KB" | "MB"
): number {
if (limitUnit === "kb" || limitUnit === "KB") {
return limitSize;
}
if (limitUnit === "mb" || limitUnit === "MB") {
return limitSize * 1024;
}
return 0;
}
/**
* @description: 判断是否没超过限制大小
* @param {RcFile} file
* @param {number} limitSize
* @param {*} limitUnit
* @return {{ success: boolean, msg?: string }}
*/
function isExceededSize(
file: RcFile,
limitSize: number,
limitUnit: "kb" | "mb" | "KB" | "MB"
): { success: boolean; msg?: string } {
const _limitSize = getLimitSize(limitSize, limitUnit);
const fileSizeToKB = file?.size / 1024;
if (fileSizeToKB <= _limitSize) {
return { success: true };
} else {
return {
success: false,
msg: `文件【${file?.name}】大小不能超过${limitSize}${limitUnit}`,
};
}
}
export function getFileSize(length: number): string {
let fileSize: string;
fileSize = (length / 1024).toFixed(2);
if (+fileSize > 1024) {
fileSize = (+fileSize / 1024).toFixed(2) + "MB";
} else {
fileSize += "KB";
}
return fileSize;
}