foundation.ts 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847
  1. import BaseFoundation, { DefaultAdapter } from '../base/foundation';
  2. import isPromise from '../utils/isPromise';
  3. import { getUuidv4 } from '../utils/uuid';
  4. import { strings, numbers } from './constants';
  5. import { getFileSize, byteKB, endsWith, mapFileTree } from './utils';
  6. const {
  7. FILE_STATUS_UPLOADING,
  8. FILE_STATUS_SUCCESS,
  9. FILE_STATUS_UPLOAD_FAIL,
  10. FILE_STATUS_VALID_FAIL,
  11. FILE_STATUS_WAIT_UPLOAD,
  12. DRAG_AREA_DEFAULT,
  13. DRAG_AREA_LEGAL,
  14. TRIGGER_AUTO,
  15. } = strings;
  16. export interface XhrError extends Error{
  17. status: XMLHttpRequest['status'];
  18. method: string;
  19. url: string;
  20. }
  21. export type FileItemStatus = 'success' | 'uploadFail' | 'validateFail' | 'validating' | 'uploading' | 'wait';
  22. export interface BaseFileItem {
  23. showReplace?: boolean; // Separately control whether the file will show the Replace button when the upload is successful
  24. showRetry?: boolean; // Separately control whether the file displays the Retry button
  25. response?: any;
  26. event?: Event; // xhr event
  27. status: FileItemStatus;
  28. name: string;
  29. size: string;
  30. uid: string;
  31. url?: string;
  32. fileInstance?: File;
  33. percent?: number;
  34. _sizeInvalid?: boolean;
  35. preview?: boolean;
  36. validateMessage?: any;
  37. shouldUpload?: boolean;
  38. [key: string]: any;
  39. }
  40. export interface CustomFile extends File {
  41. uid?: string;
  42. _sizeInvalid?: boolean;
  43. status?: string;
  44. }
  45. export interface BeforeUploadObjectResult {
  46. shouldUpload?: boolean;
  47. status?: string;
  48. autoRemove?: boolean;
  49. validateMessage?: unknown;
  50. fileInstance?: CustomFile;
  51. }
  52. export interface AfterUploadResult {
  53. autoRemove?: boolean;
  54. status?: string;
  55. validateMessage?: unknown;
  56. name?: string;
  57. }
  58. export interface UploadAdapter<P = Record<string, any>, S = Record<string, any>> extends DefaultAdapter<P, S> {
  59. notifyFileSelect: (files: Array<CustomFile>) => void;
  60. notifyError: (error: XhrError, fileInstance: File, fileList: Array<BaseFileItem>, xhr: XMLHttpRequest) => void;
  61. notifySuccess: (body: any, fileInstance: File, newFileList: Array<BaseFileItem>) => void;
  62. notifyProgress: (percent: number, fileInstance: File, newFileList: Array<BaseFileItem>) => void;
  63. notifyRemove: (file: File, newFileList: Array<BaseFileItem>, fileItem: BaseFileItem) => void;
  64. notifySizeError: (file: File, fileList: Array<BaseFileItem>) => void;
  65. notifyExceed: (files: Array<File>) => void;
  66. updateFileList: (newFileList: Array<BaseFileItem>, callback?: () => void) => void;
  67. notifyBeforeUpload: ({ file, fileList }: { file: BaseFileItem; fileList: Array<BaseFileItem> }) => boolean | BeforeUploadObjectResult | Promise<BeforeUploadObjectResult>;
  68. notifyAfterUpload: ({ response, file, fileList }: { response: any; file: BaseFileItem; fileList: Array<BaseFileItem> }) => AfterUploadResult;
  69. resetInput: () => void;
  70. resetReplaceInput: () => void;
  71. updateDragAreaStatus: (dragAreaStatus: string) => void;
  72. notifyBeforeRemove: (file: BaseFileItem, fileList: Array<BaseFileItem>) => boolean | Promise<boolean>;
  73. notifyBeforeClear: (fileList: Array<BaseFileItem>) => boolean | Promise<boolean>;
  74. notifyChange: ({ currentFile, fileList }: { currentFile: BaseFileItem | null; fileList: Array<BaseFileItem> }) => void;
  75. updateLocalUrls: (urls: Array<string>) => void;
  76. notifyClear: () => void;
  77. notifyPreviewClick: (file: any) => void;
  78. notifyDrop: (e: any, files: Array<File>, fileList: Array<BaseFileItem>) => void;
  79. notifyAcceptInvalid: (invalidFiles: Array<File>) => void;
  80. }
  81. class UploadFoundation<P = Record<string, any>, S = Record<string, any>> extends BaseFoundation<UploadAdapter<P, S>, P, S> {
  82. constructor(adapter: UploadAdapter<P, S>) {
  83. super({ ...adapter });
  84. }
  85. destroy() {
  86. this.releaseMemory();
  87. }
  88. getError({ action, xhr, message, fileName }: { action: string;xhr: XMLHttpRequest;message?: string;fileName: string }): XhrError {
  89. const status = xhr ? xhr.status : 0;
  90. const msg = message || `cannot post ${fileName} to ${action}, xhr status: ${status}'`;
  91. const err = new Error(msg) as XhrError;
  92. err.status = status;
  93. err.method = 'post';
  94. err.url = action;
  95. return err;
  96. }
  97. getBody(xhr: XMLHttpRequest): any {
  98. if (!xhr) {
  99. return;
  100. }
  101. const text = xhr.responseText || xhr.response;
  102. if (!text) {
  103. return text;
  104. }
  105. try {
  106. return JSON.parse(text);
  107. } catch (error) {
  108. return text;
  109. }
  110. }
  111. checkFileSize(file: File): boolean {
  112. const { size } = file;
  113. const { maxSize, minSize } = this.getProps();
  114. let isIllegal = false;
  115. if (size > maxSize * byteKB || size < minSize * byteKB) {
  116. isIllegal = true;
  117. }
  118. return isIllegal;
  119. }
  120. /**
  121. * 1. 选择文件
  122. * 2. transform转换. 添加uid
  123. * 3. 检查文件个数是否超出
  124. * 若超出,不添加到list中,触发onExceed,中止流程
  125. * 若未超出,执行以下流程
  126. * 4. 检查文件尺寸,添加尺寸是否合法的标识
  127. * 5. 检查uploadTrigger是否为'auto',若是执行步骤6-8
  128. * 6. 遍历文件列表触发上传
  129. * - 对尺寸不合适的不需要触发上传
  130. * 7. beforeUpload
  131. * - 对beforeUpload中设为不合法的不需要触发上传
  132. * 8. TODO: check
  133. * 9. afterUpload
  134. *
  135. * 1. Select file
  136. * 2. transform, add uid
  137. * 3. Check whether the number of files exceeds
  138. * If it exceeds, it is not added to the list, trigger onExceed, and abort the process
  139. * If it is not exceeded, execute the following process
  140. * 4. check the file size, add the size is legal logo
  141. * 5. Check whether the uploadTrigger is'auto ', if so, perform steps 6-8
  142. * 6. Traversing the file list triggers upload
  143. * - No need to trigger uploads for inappropriate sizes
  144. * 7. beforeUpload
  145. * - no need to trigger upload if beforeUpload is not set to be valid
  146. * 8. TODO: check
  147. * 9. afterUpload
  148. */
  149. handleChange(currentFileList: FileList | Array<File>): void {
  150. const invalidFiles: Array<File> = [];
  151. const { limit, transformFile, accept } = this.getProps();
  152. const { fileList } = this.getStates();
  153. let files = Array.from(currentFileList); // When the selected file
  154. if (typeof accept !== 'undefined') {
  155. files = files.filter(item => {
  156. const isValid = this.checkFileFormat(accept, item);
  157. if (!isValid) {
  158. invalidFiles.push(item);
  159. }
  160. return isValid;
  161. });
  162. if (invalidFiles.length !== 0) {
  163. this._adapter.notifyAcceptInvalid(invalidFiles);
  164. }
  165. if (files.length === 0) {
  166. return;
  167. }
  168. }
  169. files = files.map((file: CustomFile) => {
  170. if (transformFile) {
  171. file = transformFile(file);
  172. }
  173. if (!file.uid) {
  174. file.uid = getUuidv4();
  175. }
  176. if (this.checkFileSize(file)) {
  177. file._sizeInvalid = true;
  178. file.status = FILE_STATUS_VALID_FAIL;
  179. this._adapter.notifySizeError(file, fileList);
  180. }
  181. return file;
  182. });
  183. const total = fileList.length + files.length;
  184. if (typeof limit !== 'undefined') {
  185. // Determine whether the limit is exceeded
  186. if (total > limit) {
  187. this._adapter.notifyExceed(files);
  188. if (limit === 1) {
  189. // Replace the current file with the last file
  190. files = files.slice(-1);
  191. this._adapter.notifyFileSelect(files);
  192. this._adapter.resetInput();
  193. this.replaceFileList(files);
  194. return;
  195. }
  196. // If the limit is exceeded, the calculation can add a few more files and continue uploading the remaining files
  197. const restNum = limit - fileList.length;
  198. files = files.slice(0, restNum);
  199. }
  200. }
  201. this._adapter.notifyFileSelect(files);
  202. this._adapter.resetInput();
  203. this.addFilesToList(files);
  204. }
  205. // Triggered when replacing a single file
  206. handleReplaceChange(currentFileList: FileList | Array<File>): void {
  207. if (currentFileList.length === 0) {
  208. return;
  209. }
  210. const { transformFile, uploadTrigger, accept } = this.getProps();
  211. const { replaceIdx, fileList } = this.getStates();
  212. let newFile = Array.from(currentFileList).pop() as CustomFile;
  213. if (typeof accept !== 'undefined') {
  214. if (!this.checkFileFormat(accept, newFile)) {
  215. this._adapter.notifyAcceptInvalid([newFile]);
  216. return;
  217. }
  218. }
  219. if (transformFile) {
  220. newFile = transformFile(newFile);
  221. }
  222. if (!newFile.uid) {
  223. newFile.uid = getUuidv4();
  224. }
  225. if (this.checkFileSize(newFile)) {
  226. newFile._sizeInvalid = true;
  227. newFile.status = FILE_STATUS_VALID_FAIL;
  228. this._adapter.notifySizeError(newFile, fileList);
  229. }
  230. this._adapter.notifyFileSelect([newFile]);
  231. const newFileItem = this.buildFileItem(newFile, uploadTrigger);
  232. const newFileList = [...fileList];
  233. newFileList.splice(replaceIdx, 1, newFileItem);
  234. this._adapter.notifyChange({ currentFile: newFileItem, fileList: newFileList });
  235. this._adapter.updateFileList(newFileList, () => {
  236. this._adapter.resetReplaceInput();
  237. this.upload(newFileItem);
  238. });
  239. }
  240. buildFileItem(fileInstance: CustomFile, uploadTrigger: string): BaseFileItem {
  241. const { _sizeInvalid, status } = fileInstance;
  242. try {
  243. // can't use ... to get rest property on File Object
  244. delete fileInstance._sizeInvalid;
  245. delete fileInstance.status;
  246. } catch (error) {}
  247. const _file: BaseFileItem = {
  248. status: (status ? status : uploadTrigger === TRIGGER_AUTO ? FILE_STATUS_UPLOADING : FILE_STATUS_WAIT_UPLOAD) as any,
  249. name: fileInstance.name,
  250. size: getFileSize(fileInstance.size),
  251. uid: fileInstance.uid,
  252. percent: 0,
  253. fileInstance,
  254. url: this._createURL(fileInstance),
  255. };
  256. if (_sizeInvalid) {
  257. _file._sizeInvalid = true;
  258. }
  259. // If it is an image, preview; if it is a pdf, you can jump to
  260. if (this.isImage(fileInstance)) {
  261. _file.preview = true;
  262. }
  263. return _file;
  264. }
  265. replaceFileList(files: Array<CustomFile>): void {
  266. const { uploadTrigger } = this.getProps();
  267. const currentFiles = files.map(item => this.buildFileItem(item, uploadTrigger));
  268. this._adapter.notifyChange({ fileList: currentFiles, currentFile: currentFiles[0] });
  269. this._adapter.updateFileList(currentFiles, () => {
  270. if (uploadTrigger === TRIGGER_AUTO) {
  271. this.startUpload(currentFiles);
  272. }
  273. });
  274. }
  275. addFilesToList(files: Array<CustomFile>): void {
  276. const fileList = this.getState('fileList').slice();
  277. const { uploadTrigger } = this.getProps();
  278. const currentFiles = files.map(item => this.buildFileItem(item, uploadTrigger));
  279. currentFiles.forEach(file => {
  280. const index = fileList.findIndex((item: BaseFileItem) => item.uid === file.uid);
  281. if (index !== -1) {
  282. fileList[index] = file;
  283. } else {
  284. fileList.push(file);
  285. this._adapter.notifyChange({ fileList, currentFile: file });
  286. }
  287. });
  288. this._adapter.updateFileList(fileList, () => {
  289. if (uploadTrigger === TRIGGER_AUTO) {
  290. this.startUpload(currentFiles);
  291. }
  292. });
  293. }
  294. // 插入多个文件到指定位置
  295. // Insert files to the specified location
  296. insertFileToList(files: Array<CustomFile>, index:number): void {
  297. const { limit, transformFile, accept, uploadTrigger } = this.getProps();
  298. const { fileList } = this.getStates();
  299. const unAcceptFileList = [];
  300. // 当次选中的文件
  301. // current selected file
  302. let currentFileList = Array.from(files);
  303. if (typeof accept !== 'undefined') {
  304. currentFileList = currentFileList.filter(item => {
  305. const isValid = this.checkFileFormat(accept, item);
  306. if (!isValid) {
  307. unAcceptFileList.push(item);
  308. }
  309. return isValid;
  310. });
  311. if (unAcceptFileList.length !== 0) {
  312. this._adapter.notifyAcceptInvalid(unAcceptFileList);
  313. }
  314. if (currentFileList.length === 0) {
  315. return;
  316. }
  317. }
  318. currentFileList = currentFileList.map(file => {
  319. if (!file.uid) {
  320. file.uid = getUuidv4();
  321. }
  322. if (this.checkFileSize(file)) {
  323. file._sizeInvalid = true;
  324. file.status = FILE_STATUS_VALID_FAIL;
  325. this._adapter.notifySizeError(file, fileList);
  326. }
  327. if (transformFile) {
  328. file = transformFile(file);
  329. }
  330. return file;
  331. });
  332. const total = fileList.length + currentFileList.length;
  333. if (typeof limit !== 'undefined') {
  334. // 判断是否超出限制
  335. // Determine whether the limit is exceeded
  336. if (total > limit) {
  337. if (limit === 1) {
  338. // 使用最后面的文件对当前文件进行替换
  339. // Use the last file to replace the current file
  340. currentFileList = currentFileList.slice(-1);
  341. this._adapter.notifyFileSelect(currentFileList);
  342. this._adapter.resetInput();
  343. this.replaceFileList(currentFileList);
  344. return;
  345. }
  346. // 如果超出了限制,则计算还能添加几个文件,将剩余的文件继续上传
  347. // If the limit is exceeded, several files can be added to the calculation, and the remaining files will continue to be uploaded
  348. const restNum = limit - fileList.length;
  349. currentFileList = currentFileList.slice(0, restNum);
  350. this._adapter.notifyExceed(currentFileList);
  351. }
  352. }
  353. const fileItemList = currentFileList.map(file => this.buildFileItem(file, uploadTrigger));
  354. const newFileList = fileList.slice();
  355. if (typeof index !== 'undefined') {
  356. newFileList.splice(index, 0, ...fileItemList);
  357. } else {
  358. newFileList.push(...fileItemList);
  359. }
  360. this._adapter.notifyFileSelect(currentFileList);
  361. this._adapter.notifyChange({ fileList: newFileList, currentFile: null });
  362. this._adapter.updateFileList(newFileList, () => {
  363. if (uploadTrigger === TRIGGER_AUTO) {
  364. this.startUpload(fileItemList);
  365. }
  366. });
  367. }
  368. /* istanbul ignore next */
  369. manualUpload(): void {
  370. // find the list of files that have not been uploaded
  371. const waitToUploadFileList = this.getState('fileList').filter((item: BaseFileItem) => item.status === FILE_STATUS_WAIT_UPLOAD);
  372. this.startUpload(waitToUploadFileList);
  373. }
  374. startUpload(fileList: Array<BaseFileItem>): void {
  375. fileList.forEach(file => {
  376. if (!file._sizeInvalid) {
  377. this.upload(file);
  378. }
  379. });
  380. }
  381. upload(file: BaseFileItem): void {
  382. const { beforeUpload } = this.getProps();
  383. if (typeof beforeUpload === 'undefined') {
  384. this.post(file);
  385. return;
  386. }
  387. if (typeof beforeUpload === 'function') {
  388. const { fileList } = this.getStates();
  389. const buResult = this._adapter.notifyBeforeUpload({ file, fileList });
  390. switch (true) {
  391. // sync validate - boolean
  392. case buResult === true: {
  393. this.post(file);
  394. break;
  395. }
  396. case buResult === false: {
  397. const newResult = { shouldUpload: false, status: strings.FILE_STATUS_VALID_FAIL };
  398. this.handleBeforeUploadResultInObject(newResult, file);
  399. break;
  400. }
  401. // async validate
  402. case buResult && isPromise(buResult): {
  403. Promise.resolve(buResult as Promise<BeforeUploadObjectResult>).then(
  404. resolveData => {
  405. let newResult = { shouldUpload: true };
  406. const typeOfResolveData = Object.prototype.toString.call(resolveData).slice(8, -1);
  407. if (typeOfResolveData === 'Object') {
  408. newResult = { ...newResult, ...resolveData };
  409. }
  410. this.handleBeforeUploadResultInObject(newResult, file);
  411. },
  412. rejectVal => {
  413. let newResult = { shouldUpload: false, status: strings.FILE_STATUS_VALID_FAIL };
  414. const typeOfRejectData = Object.prototype.toString.call(rejectVal).slice(8, -1);
  415. if (typeOfRejectData === 'Object') {
  416. newResult = { ...newResult, ...rejectVal };
  417. }
  418. this.handleBeforeUploadResultInObject(newResult, file);
  419. });
  420. break;
  421. }
  422. // sync validate - object
  423. case typeof buResult === 'object':
  424. // inject to fileList
  425. this.handleBeforeUploadResultInObject(buResult as BeforeUploadObjectResult, file);
  426. break;
  427. default:
  428. break;
  429. }
  430. }
  431. }
  432. // handle beforeUpload result when it's an object
  433. handleBeforeUploadResultInObject(buResult: Partial<BeforeUploadObjectResult>, file: BaseFileItem): void {
  434. const { shouldUpload, status, autoRemove, validateMessage, fileInstance } = buResult;
  435. let newFileList: Array<BaseFileItem> = this.getState('fileList').slice();
  436. if (autoRemove) {
  437. newFileList = newFileList.filter(item => item.uid !== file.uid);
  438. } else {
  439. const index = this._getFileIndex(file, newFileList);
  440. if (index < 0) {
  441. return;
  442. }
  443. status ? (newFileList[index].status = status as any) : null;
  444. validateMessage ? (newFileList[index].validateMessage = validateMessage) : null;
  445. if (fileInstance) {
  446. fileInstance.uid = file.uid; // reuse recent file uid
  447. newFileList[index].fileInstance = fileInstance;
  448. newFileList[index].size = getFileSize(fileInstance.size);
  449. newFileList[index].name = fileInstance.name;
  450. }
  451. newFileList[index].shouldUpload = shouldUpload;
  452. }
  453. this._adapter.updateFileList(newFileList);
  454. this._adapter.notifyChange({ fileList: newFileList, currentFile: file });
  455. if (shouldUpload) {
  456. this.post(file);
  457. }
  458. }
  459. post(file: BaseFileItem): void {
  460. const { fileInstance } = file;
  461. const option = this.getProps();
  462. if (typeof XMLHttpRequest === 'undefined') {
  463. return;
  464. }
  465. const xhr = new XMLHttpRequest();
  466. const formData = new FormData();
  467. const { action } = option;
  468. // add data
  469. let { data } = option;
  470. if (data) {
  471. if (typeof data === 'function') {
  472. data = data(fileInstance);
  473. }
  474. Object.keys(data).forEach(key => {
  475. formData.append(key, data[key]);
  476. });
  477. }
  478. // add file
  479. const fileName = option.name || option.fileName || fileInstance.name;
  480. if (option.customRequest) {
  481. return option.customRequest({
  482. fileName,
  483. data,
  484. file,
  485. fileInstance,
  486. onProgress: (e: ProgressEvent) => this.handleProgress({ e, fileInstance }),
  487. onError: (userXhr: XMLHttpRequest, e: ProgressEvent) => this.handleError({ e, xhr: userXhr, fileInstance }),
  488. onSuccess: (response: any, e: ProgressEvent) => this.handleSuccess({ response, fileInstance, e, isCustomRequest: true }),
  489. withCredentials: option.withCredentials,
  490. action: option.action,
  491. });
  492. }
  493. formData.append(fileName, fileInstance);
  494. xhr.open('post', action, true);
  495. if (option.withCredentials && 'withCredentials' in xhr) {
  496. xhr.withCredentials = true;
  497. }
  498. if (xhr.upload) {
  499. xhr.upload.onprogress = (e: ProgressEvent): void => this.handleProgress({ e, fileInstance });
  500. }
  501. // Callback function after upload is completed
  502. xhr.onload = (e: ProgressEvent): void => this.handleOnLoad({ e, xhr, fileInstance });
  503. xhr.onerror = (e: ProgressEvent): void => this.handleError({ e, xhr, fileInstance });
  504. // add headers
  505. let headers = option.headers || {};
  506. if (typeof headers === 'function') {
  507. headers = headers(fileInstance);
  508. }
  509. for (const item in headers) {
  510. if (Object.prototype.hasOwnProperty.call(headers, item) && headers[item] !== null) {
  511. xhr.setRequestHeader(item, headers[item]);
  512. }
  513. }
  514. xhr.send(formData);
  515. }
  516. handleProgress({ e, fileInstance }: { e: ProgressEvent; fileInstance: File }): void {
  517. const { fileList } = this.getStates();
  518. const newFileList = fileList.slice();
  519. let percent = 0;
  520. if (e.total > 0) {
  521. percent = Number(((e.loaded / e.total) * 100 * numbers.PROGRESS_COEFFICIENT).toFixed(0)) || 0;
  522. }
  523. const index = this._getFileIndex(fileInstance, newFileList);
  524. if (index < 0) {
  525. return;
  526. }
  527. newFileList[index].percent = percent;
  528. newFileList[index].status = FILE_STATUS_UPLOADING;
  529. this._adapter.notifyProgress(percent, fileInstance, newFileList);
  530. this._adapter.updateFileList(newFileList);
  531. this._adapter.notifyChange({ fileList: newFileList, currentFile: newFileList[index] });
  532. }
  533. handleOnLoad({ e, xhr, fileInstance }: { e: ProgressEvent; xhr: XMLHttpRequest; fileInstance: File }): void {
  534. const { fileList } = this.getStates();
  535. const index = this._getFileIndex(fileInstance, fileList);
  536. if (index < 0) {
  537. return;
  538. }
  539. if (xhr.status < 200 || xhr.status >= 300) {
  540. this.handleError({ e, xhr, fileInstance });
  541. } else {
  542. this.handleSuccess({ e, xhr, fileInstance, index } as any);
  543. }
  544. }
  545. handleSuccess({ e, fileInstance, isCustomRequest = false, xhr, response }: { e: ProgressEvent; fileInstance: CustomFile; isCustomRequest?: boolean; xhr?: XMLHttpRequest; response?: any }): void {
  546. const { fileList } = this.getStates();
  547. let body: any = null;
  548. const index = this._getFileIndex(fileInstance, fileList);
  549. if (index < 0) {
  550. return;
  551. }
  552. if (isCustomRequest) {
  553. // use when pass customRequest
  554. body = response;
  555. } else {
  556. body = this.getBody(xhr);
  557. }
  558. const newFileList = fileList.slice();
  559. const { afterUpload } = this.getProps();
  560. newFileList[index].status = FILE_STATUS_SUCCESS;
  561. newFileList[index].percent = 100;
  562. this._adapter.notifyProgress(100, fileInstance, newFileList);
  563. newFileList[index].response = body;
  564. e ? (newFileList[index].event = e) : null;
  565. if (afterUpload && typeof afterUpload === 'function') {
  566. const { autoRemove, status, validateMessage, name } =
  567. this._adapter.notifyAfterUpload({
  568. response: body,
  569. file: newFileList[index],
  570. fileList: newFileList,
  571. }) || {};
  572. status ? (newFileList[index].status = status) : null;
  573. validateMessage ? (newFileList[index].validateMessage = validateMessage) : null;
  574. name ? (newFileList[index].name = name) : null;
  575. autoRemove ? newFileList.splice(index, 1) : null;
  576. }
  577. this._adapter.notifySuccess(body, fileInstance, newFileList);
  578. this._adapter.notifyChange({ fileList: newFileList, currentFile: newFileList[index] });
  579. this._adapter.updateFileList(newFileList);
  580. }
  581. _getFileIndex(file: CustomFile | BaseFileItem, fileList: Array<BaseFileItem>): number {
  582. return fileList.findIndex(item => item.uid === file.uid);
  583. }
  584. handleRemove(file: BaseFileItem): void {
  585. const { disabled } = this.getProps();
  586. if (disabled) {
  587. return;
  588. }
  589. const { fileList } = this.getStates();
  590. Promise.resolve(this._adapter.notifyBeforeRemove(file, fileList)).then(res => {
  591. // prevent remove while user return false
  592. if (res === false) {
  593. return;
  594. }
  595. const newFileList = fileList.slice();
  596. const index = this._getFileIndex(file, fileList);
  597. if (index < 0) {
  598. return;
  599. }
  600. newFileList.splice(index, 1);
  601. this._adapter.notifyRemove(file.fileInstance, newFileList, file);
  602. this._adapter.updateFileList(newFileList);
  603. this._adapter.notifyChange({ fileList: newFileList, currentFile: file });
  604. });
  605. }
  606. handleError({ e, xhr, fileInstance }: { e: ProgressEvent;xhr: XMLHttpRequest;fileInstance: CustomFile }): void {
  607. const { fileList } = this.getStates();
  608. const index = this._getFileIndex(fileInstance, fileList);
  609. if (index < 0) {
  610. return;
  611. }
  612. const { action } = this.getProps();
  613. const newFileList = fileList.slice();
  614. const error = this.getError({ action, xhr, fileName: fileInstance.name });
  615. newFileList[index].status = FILE_STATUS_UPLOAD_FAIL;
  616. newFileList[index].response = error;
  617. newFileList[index].event = e;
  618. this._adapter.notifyError(error, fileInstance, newFileList, xhr);
  619. this._adapter.updateFileList(newFileList);
  620. this._adapter.notifyChange({ currentFile: newFileList[index], fileList: newFileList });
  621. }
  622. handleClear() {
  623. const { disabled } = this.getProps();
  624. const { fileList } = this.getStates();
  625. if (disabled) {
  626. return;
  627. }
  628. Promise.resolve(this._adapter.notifyBeforeClear(fileList)).then(res => {
  629. if (res === false) {
  630. return;
  631. }
  632. this._adapter.updateFileList([]);
  633. this._adapter.notifyClear();
  634. this._adapter.notifyChange({ fileList: [] } as any);
  635. });
  636. }
  637. _createURL(fileInstance: CustomFile): string {
  638. // https://stackoverflow.com/questions/31742072/filereader-vs-window-url-createobjecturl
  639. const url = URL.createObjectURL(fileInstance);
  640. const { localUrls } = this.getStates();
  641. const newUrls = localUrls.slice();
  642. newUrls.push(url);
  643. this._adapter.updateLocalUrls(newUrls);
  644. return url;
  645. }
  646. // 释放预览文件所占用的内存
  647. // Release memory used by preview files
  648. releaseMemory(): void {
  649. const { localUrls }: { localUrls: Array<string> } = this.getStates();
  650. localUrls.forEach(url => {
  651. this._releaseBlob(url);
  652. });
  653. }
  654. _releaseBlob(url: string): void {
  655. try {
  656. URL.revokeObjectURL(url);
  657. } catch (error) {
  658. console.log(error);
  659. }
  660. }
  661. isImage(file: CustomFile): boolean {
  662. return /(webp|svg|png|gif|jpg|jpeg|bmp|dpg)$/i.test(file.type);
  663. }
  664. /* istanbul ignore next */
  665. isMultiple(): boolean {
  666. return Boolean(this.getProp('multiple'));
  667. }
  668. _dragEnterTarget: EventTarget;
  669. handleDragEnter(e: any): void {
  670. e.preventDefault();
  671. e.stopPropagation();
  672. this._dragEnterTarget = e.currentTarget;
  673. const { disabled } = this.getProps();
  674. if (!disabled) {
  675. this._adapter.updateDragAreaStatus(DRAG_AREA_LEGAL);
  676. }
  677. }
  678. async handleDirectoryDrop(e: any): Promise<void> {
  679. const fileList = this.getState('fileList').slice();
  680. const items = [].slice.call(e.dataTransfer.items);
  681. const files = await mapFileTree(items);
  682. this.handleChange(files);
  683. this._adapter.updateDragAreaStatus(DRAG_AREA_DEFAULT);
  684. this._adapter.notifyDrop(e, files, fileList);
  685. }
  686. handleDrop(e: any): void {
  687. // Block file opening in browser
  688. e.preventDefault();
  689. e.stopPropagation();
  690. const { disabled, directory } = this.getProps();
  691. const fileList = this.getState('fileList').slice();
  692. if (!disabled) {
  693. if (directory) {
  694. this.handleDirectoryDrop(e);
  695. return;
  696. }
  697. const files: File[] = Array.from(e.dataTransfer.files);
  698. this.handleChange(files);
  699. this._adapter.updateDragAreaStatus(DRAG_AREA_DEFAULT);
  700. this._adapter.notifyDrop(e, files, fileList);
  701. }
  702. }
  703. handleDragOver(e: any): void {
  704. e.preventDefault();
  705. e.stopPropagation();
  706. }
  707. handleDragLeave(e: any): void {
  708. e.preventDefault();
  709. e.stopPropagation();
  710. // 防止拖拽进入子元素时触发的dragLeave也被处理
  711. // Prevent dragLeave triggered when dragging into a child element is also handled
  712. // https://stackoverflow.com/questions/7110353/html5-dragleave-fired-when-hovering-a-child-element
  713. if (this._dragEnterTarget === e.target) {
  714. this._adapter.updateDragAreaStatus(DRAG_AREA_DEFAULT);
  715. }
  716. }
  717. // 拖拽上传时,需要对文件的格式进行校验
  718. // When dragging and uploading, you need to verify the file format
  719. checkFileFormat(accept: string, file: File): boolean {
  720. const acceptTypes = accept
  721. .split(',')
  722. .map(type => type.trim())
  723. .filter(type => type);
  724. const mimeType = file.type || '';
  725. // Get the large class to which MIMEtype belongs, eg: image/jpeg = > image, application/= > application
  726. const baseMimeType = mimeType.replace(/\/.*$/, '');
  727. return acceptTypes.some(type => {
  728. // When accepted as a suffix filename such as [.jpeg]
  729. if (type.charAt(0) === '.') {
  730. const fileName = file.name || '';
  731. const acceptExtension = type.split('.').pop().toLowerCase();
  732. return endsWith(fileName.toLowerCase(), acceptExtension);
  733. }
  734. // When accepted as a general class such as [image/*] or [video/*]
  735. if (/\/\*$/.test(type)) {
  736. const acceptBaseMimeType = type.replace(/\/.*$/, '');
  737. return baseMimeType === acceptBaseMimeType;
  738. }
  739. // When accepted as a full MIME types string
  740. if (/^[^\/]+\/[^\/]+$/.test(type)) {
  741. return mimeType === type;
  742. }
  743. return false;
  744. });
  745. }
  746. retry(fileItem: BaseFileItem): void {
  747. const { onRetry } = this.getProps();
  748. if (onRetry && typeof onRetry === 'function') {
  749. onRetry(fileItem);
  750. }
  751. this.post(fileItem);
  752. }
  753. handlePreviewClick(fileItem: BaseFileItem): void {
  754. this._adapter.notifyPreviewClick(fileItem);
  755. }
  756. }
  757. export default UploadFoundation;