上传文件怎么做

5/25/2022 React QS
import { UploadOutlined, VerticalAlignBottomOutlined, InfoCircleFilled } from '@ant-design/icons';
import { Button, Modal, Upload, message, notification, Tabs } from 'antd';
import React, { useCallback, useMemo, useState } from 'react';
import { request } from 'umi';

import type { ButtonProps , UploadProps } from 'antd';
import type { RcFile } from 'antd/lib/upload';
import type { UploadRequestOption } from 'rc-upload/lib/interface';

import { uploadImg } from '@/services/device';
import type { ExcelImportResult } from '@/types/ExcelImportResult';
import { exportExcel, getErrorMsg, hasValue } from '@/utils/utils';
import {saveAs} from 'file-saver';

const { TabPane } = Tabs;

function createGuid() {
  function S4() {
    return ((1 + Math.random()) * 0x10000 || 0).toString(16).substring(1);
  }
  return `${S4() + S4()}-${S4()}-${S4()}-${S4()}-${S4()}${S4()}${S4()}`;
}

export type UploadSuccessCallbackFn = (response: any) => void;

export interface ImportProps {
  /**
   * 弹出框标题
   */
  title: string;
  /**
   * 下载模板的url
   */
  downloadUrl: string; // 下载模板的url
  /**
   * 上传文件分类-moduleType(向后台要)
   */
  moduleType: string;
  /**
   * 文件上传请求url
   * 默认请求地址: /api/file/UploadToFileSystem
   */
  actionUrl?: string;
  /**
   * 导入确认提交url
   */
  submitUrl: string; // 导入文件的url
  /**
   * 请求额外参数
   */
  params?: Record<string, any>;
  /**
   * 请求成功回调函数
   * 导入成功后刷新表格(获取表格数据的方法)
   */
  getTableList: UploadSuccessCallbackFn;
  /**
   * 样式名
   */
  className?: string;
  /**
   * 导入按钮样式
   */
  buttonProps?: ButtonProps;
  /**
   * 重传次数
   */
  retryCount?: number;
  /**
   * 禁用覆盖导入
   * @default false
   */
  noCover?: boolean;
  /**
   * 是否上传成功校验函数
   * @param response
   */
  validateFn?: (response: any) => ExcelImportResult;
}

const BatchImport: React.FC<ImportProps> = (props) => {
  const [importModalShow, setImportModalShow] = useState(false);
  const [excelFilePath, setExcelFilePath] = useState('');
  const [uploadType, setUploadType] = useState('1');
  const [fileList, setFileList] = useState([]);

  const chunkSize = 1024 * 1024;

  const retryCount = useMemo(() => {
    if (hasValue(props.retryCount)) {
      return props.retryCount!;
    }
    return 0;
  }, [props.retryCount]);

  const actionUrl = useMemo(() => {
    return props.actionUrl ?? '/api/file/UploadToFileSystem';
  }, [props.actionUrl]);

  // 批量导入
  const importData = () => {
    setExcelFilePath('');
    setFileList([]);
    setImportModalShow(true);
  };

  // 增量导入 or 覆盖导入
  const changeUploadType = (key: string) => {
    setUploadType(key);
  };

  // 下载模板
  const getTemplate = useCallback(() => {
    // window.location.href = props.downloadUrl;
    request(props.downloadUrl, {
      responseType: 'blob',
    }).then((res: any) => {
      const blob = new Blob([res], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      });
      console.log(blob);
      const fileName = `${props.title}_模板.xlsx`;
      exportExcel(blob, fileName);
    });
  }, [props.downloadUrl, props.title]);

  const beforeUploadFile = (file: any) => {
    const isCorrectFile =
      file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
      file.type === 'application/vnd.ms-excel';
    if (!isCorrectFile) {
      message.error('请上传xls或xlsx格式的文件').then();
    }
    return isCorrectFile;
  };

  const fileUpload = (
    option: UploadRequestOption,
    guid: string,
    partNum: number,
    partTotal: number,
    requestList: { request: Promise<any>; status: string; retryCount: number }[] | undefined[],
    callback: {
      onSuccess: (response: any) => void;
      onError: (err: Error) => void;
      onProgress: (percent: number) => void;
    },
  ) => {
    const file = option.file as RcFile;
    const formData = new FormData();
    // 将文件进行分段
    const chunkedFile = file.slice(partNum * chunkSize, (partNum + 1) * chunkSize);
    formData.append('file', chunkedFile);
    formData.append('name', file.name);
    formData.append('chunk', `${partNum}`);
    formData.append('totalFileSize', `${file.size}`);
    formData.append('moduleType', props.moduleType);
    formData.append('maxChunk', `${partTotal}`);
    formData.append('guid', guid);
    const promise = uploadImg(formData)
      .then((res) => {
        const config = requestList[partNum];
        if (res.code === 200) {
          callback.onProgress(parseInt(String(((partNum + 1) / partTotal) * 100), 10));
          if (partNum + 1 === partTotal) {
            requestList.splice(partNum, 1, {
              request: promise,
              status: 'resolved',
              retryCount: config?.retryCount ?? 0,
            });
            const { onSuccess } = callback;
            onSuccess(res);
          } else if (partNum < partTotal) {
            const req = fileUpload(option, guid, partNum + 1, partTotal, requestList, callback);
            requestList.splice(partNum + 1, 1, {
              request: req,
              status: 'resolved',
              retryCount: config?.retryCount ?? 0,
            });
          }
        } else {
          throw new Error(getErrorMsg(res));
        }
      })
      .catch((err) => {
        const config = requestList[partNum];
        if (config) {
          // 进行错误重传
          if (config.retryCount < retryCount) {
            const req = fileUpload(option, guid, partNum, partTotal, requestList, callback);
            requestList.splice(partNum, 1, {
              request: req,
              status: 'pending',
              retryCount: config.retryCount + 1,
            });
          } else {
            requestList.splice(partNum, 1, {
              ...config,
              status: 'error',
            });
            const { onError } = callback;
            onError(err);
          }
        } else {
          // 增加处理-不需要重传处
          if (retryCount) {
            const req = fileUpload(option, guid, partNum, partTotal, requestList, callback);
            requestList.splice(partNum, 1, {
              request: req,
              status: 'pending',
              retryCount: 1,
            });
          }
          requestList.splice(partNum, 1, {
            request: Promise.reject(),
            status: 'error',
            retryCount: 0,
          });
          const { onError } = callback;
          onError(err);
        }
      });
    return promise;
  };

  const customRequest = async (option: UploadRequestOption) => {
    const { onProgress, onError, onSuccess } = option;
    const file = option.file as RcFile;
    const len = Math.ceil(file.size / chunkSize) || 1;
    const requestList = new Array(len);
    const guid = createGuid();

    // 遍历请求列表,将文件分片并进行请求后,替换对应列表项。
    // 请求中增加根据更新、错误重传(3次失败后放弃,整个文件失败)
    const req = fileUpload(option, guid, 0, len, requestList, {
      onProgress: (percent) => onProgress?.({ percent } as any),
      onError: (err: Error) => onError?.(err),
      onSuccess: (res) => {
        onSuccess?.(res.data);
        if (res.data?.data?.completed && res.data?.data?.fileUrl) {
          setExcelFilePath(res.data?.data?.fileUrl);
        }
      },
    });

    req.catch((err) => {
      message.error(getErrorMsg(err));
    });
  };

  const changeFile = (info: any) => {
    let fList: any = [...info.fileList];
    fList = fList.slice(-1);
    if (!fList.length) {
      setExcelFilePath('');
    }
    setFileList(fList);
  };

  const uploadProps: UploadProps = {
    name: 'file',
    action: actionUrl,
    headers: {
      authorization: 'authorization-text',
    },
    onChange: changeFile,
    beforeUpload: beforeUploadFile,
    customRequest,
  };

  // 确定
  const sureImport = async () => {
    if (excelFilePath === '') {
      message.error('请上传xls或xlsx格式的文件').then();
      return false;
    }
    const params = {
      filePath: excelFilePath,
      override: uploadType !== '1',
    };
    try {
      const response = await request(props.submitUrl, {
        method: 'POST',
        data: { ...params, ...(props.params ?? {}) },
      });
      if (response && response.code === 200) {
        let result: ExcelImportResult | undefined;
        if (props.validateFn) {
          result = props.validateFn(response.data);
        } else {
          result = response.data?.data;
        }
        if (result?.importSuccess) {
          notification.success({
            message: '导入成功',
            description: (
              <div>
                <div>共计 {result.count} 条数据</div>
                <div>导入日期:{new Date().toLocaleString()}</div>
              </div>
            ),
          });
          setImportModalShow(false);
          setTimeout(() => {
            // 默认延时进行通知,防止后续渲染过多导致卡顿
            props.getTableList(response.data);
          }, 50);
        } else if (result?.errorExcelPath) {
          const url = `${BASE_URL_IMAGE}/UpLoads/${props.moduleType}/${result.errorExcelPath}`;
          notification.error({
            message: '导入失败',
            description: (
              <div>
                <div>上传的数据填写不正确。我们已将这部分标示并生成文件,点击下方按钮下载</div>
                <div>
                  <a href={url}>当前导入模板_校验</a>
                </div>
              </div>
            ),
          });
          setImportModalShow(false);
        } else {
          message.error('导入异常');
        }
      } else {
        setImportModalShow(false);
        message.error(getErrorMsg(response.message));
      }
    } catch (err) {
      console.error(err);
      // 错误内容已由全局加入,暂不重复显示
      // message.error(getErrorMsg(err));
    }
  };

  // 取消
  const cancelImport = () => {
    setExcelFilePath('');
    setFileList([]);
    setImportModalShow(false);
  };

  return (
    <div className={props.className}>
      <Button
        { ...props.buttonProps }
        onClick={importData}
      >
        {props.buttonProps?.children ?? '导入'}
      </Button>

      <Modal
        title={`批量导入${props.title}`}
        okText="校验导入"
        visible={importModalShow}
        onOk={sureImport}
        onCancel={cancelImport}
      >
        <div>
          {!props.noCover && (
            <Tabs defaultActiveKey="1" style={{ marginTop: '-10px' }} onChange={changeUploadType}>
              <TabPane tab="增量导入" key="1">
                <InfoCircleFilled style={{ color: '#007aff', margin: '0 10px' }} />
                在已有数据的基础上增加导入全新的数据
              </TabPane>
              <TabPane tab="覆盖导入" key="2">
                <InfoCircleFilled style={{ color: '#007aff', margin: '0 10px' }} />
                导入全新数据的同时,替换与已有数据重复的数据
              </TabPane>
            </Tabs>
          )}
          <div style={{ marginTop: props.noCover ? 0 : '40px' }}>
            <Button onClick={getTemplate} style={{ marginRight: '30px' }}>
              <VerticalAlignBottomOutlined />
              下载空白模板
            </Button>
            <Upload {...uploadProps} fileList={fileList}>
              <Button>
                <UploadOutlined />
                上传模板
              </Button>
            </Upload>
          </div>
        </div>
      </Modal>
    </div>
  );
};

export default BatchImport;

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
Last Updated: 5/25/2022, 9:06:54 AM