foundation.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763
  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?: unknown;
  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 isIlligal = false;
  115. if (size > maxSize * byteKB || size < minSize * byteKB) {
  116. isIlligal = true;
  117. }
  118. return isIlligal;
  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. manualUpload(): void {
  295. // find the list of files that have not been uploaded
  296. const waitToUploadFileList = this.getState('fileList').filter((item: BaseFileItem) => item.status === FILE_STATUS_WAIT_UPLOAD);
  297. this.startUpload(waitToUploadFileList);
  298. }
  299. startUpload(fileList: Array<BaseFileItem>): void {
  300. fileList.forEach(file => {
  301. if (!file._sizeInvalid) {
  302. this.upload(file);
  303. }
  304. });
  305. }
  306. upload(file: BaseFileItem): void {
  307. const { beforeUpload } = this.getProps();
  308. if (typeof beforeUpload === 'undefined') {
  309. this.post(file);
  310. return;
  311. }
  312. if (typeof beforeUpload === 'function') {
  313. const { fileList } = this.getStates();
  314. const buResult = this._adapter.notifyBeforeUpload({ file, fileList });
  315. switch (true) {
  316. // sync valiate - boolean
  317. case buResult === true: {
  318. this.post(file);
  319. break;
  320. }
  321. case buResult === false: {
  322. const newResult = { shouldUpload: false, status: strings.FILE_STATUS_VALID_FAIL };
  323. this.handleBeforeUploadResultInObject(newResult, file);
  324. break;
  325. }
  326. // async validate
  327. case buResult && isPromise(buResult): {
  328. Promise.resolve(buResult as Promise<BeforeUploadObjectResult>).then(
  329. resloveData => {
  330. let newResult = { shouldUpload: true };
  331. const typeOfResloveData = Object.prototype.toString.call(resloveData).slice(8, -1);
  332. if (typeOfResloveData === 'Object') {
  333. newResult = { ...newResult, ...resloveData };
  334. }
  335. this.handleBeforeUploadResultInObject(newResult, file);
  336. },
  337. rejectVal => {
  338. let newResult = { shouldUpload: false, status: strings.FILE_STATUS_VALID_FAIL };
  339. const typeOfRejectData = Object.prototype.toString.call(rejectVal).slice(8, -1);
  340. if (typeOfRejectData === 'Object') {
  341. newResult = { ...newResult, ...rejectVal };
  342. }
  343. this.handleBeforeUploadResultInObject(newResult, file);
  344. });
  345. break;
  346. }
  347. // sync validate - object
  348. case typeof buResult === 'object':
  349. // inject to fileList
  350. this.handleBeforeUploadResultInObject(buResult as BeforeUploadObjectResult, file);
  351. break;
  352. default:
  353. break;
  354. }
  355. }
  356. }
  357. // handle beforeUpload result when it's an object
  358. handleBeforeUploadResultInObject(buResult: Partial<BeforeUploadObjectResult>, file: BaseFileItem): void {
  359. const { shouldUpload, status, autoRemove, validateMessage, fileInstance } = buResult;
  360. let newFileList: Array<BaseFileItem> = this.getState('fileList').slice();
  361. if (autoRemove) {
  362. newFileList = newFileList.filter(item => item.uid !== file.uid);
  363. } else {
  364. const index = this._getFileIndex(file, newFileList);
  365. if (index < 0) {
  366. return;
  367. }
  368. status ? (newFileList[index].status = status as any) : null;
  369. validateMessage ? (newFileList[index].validateMessage = validateMessage) : null;
  370. if (fileInstance) {
  371. fileInstance.uid = file.uid; // reuse recent file uid
  372. newFileList[index].fileInstance = fileInstance;
  373. newFileList[index].size = getFileSize(fileInstance.size);
  374. newFileList[index].name = fileInstance.name;
  375. }
  376. newFileList[index].shouldUpload = shouldUpload;
  377. }
  378. this._adapter.updateFileList(newFileList);
  379. this._adapter.notifyChange({ fileList: newFileList, currentFile: file });
  380. if (shouldUpload) {
  381. this.post(file);
  382. }
  383. }
  384. post(file: BaseFileItem): void {
  385. const { fileInstance } = file;
  386. const option = this.getProps();
  387. if (typeof XMLHttpRequest === 'undefined') {
  388. return;
  389. }
  390. const xhr = new XMLHttpRequest();
  391. const formData = new FormData();
  392. const { action } = option;
  393. // add data
  394. let { data } = option;
  395. if (data) {
  396. if (typeof data === 'function') {
  397. data = data(fileInstance);
  398. }
  399. Object.keys(data).forEach(key => {
  400. formData.append(key, data[key]);
  401. });
  402. }
  403. // add file
  404. const fileName = option.name || option.fileName || fileInstance.name;
  405. if (option.customRequest) {
  406. return option.customRequest({
  407. fileName,
  408. data,
  409. file,
  410. fileInstance,
  411. onProgress: (e: ProgressEvent) => this.handleProgress({ e, fileInstance }),
  412. onError: (userXhr: XMLHttpRequest, e: ProgressEvent) => this.handleError({ e, xhr: userXhr, fileInstance }),
  413. onSuccess: (response: any, e: ProgressEvent) => this.handleSuccess({ response, fileInstance, e, isCustomRequest: true }),
  414. withCredentials: option.withCredentials,
  415. action: option.action,
  416. });
  417. }
  418. formData.append(fileName, fileInstance);
  419. xhr.open('post', action, true);
  420. if (option.withCredentials && 'withCredentials' in xhr) {
  421. xhr.withCredentials = true;
  422. }
  423. if (xhr.upload) {
  424. xhr.upload.onprogress = (e: ProgressEvent): void => this.handleProgress({ e, fileInstance });
  425. }
  426. // Callback function after upload is completed
  427. xhr.onload = (e: ProgressEvent): void => this.handleOnLoad({ e, xhr, fileInstance });
  428. xhr.onerror = (e: ProgressEvent): void => this.handleError({ e, xhr, fileInstance });
  429. // add headers
  430. let headers = option.headers || {};
  431. if (typeof headers === 'function') {
  432. headers = headers(fileInstance);
  433. }
  434. for (const item in headers) {
  435. if (Object.prototype.hasOwnProperty.call(headers, item) && headers[item] !== null) {
  436. xhr.setRequestHeader(item, headers[item]);
  437. }
  438. }
  439. xhr.send(formData);
  440. }
  441. handleProgress({ e, fileInstance }: { e: ProgressEvent; fileInstance: File }): void {
  442. const { fileList } = this.getStates();
  443. const newFileList = fileList.slice();
  444. let percent = 0;
  445. if (e.total > 0) {
  446. percent = Number(((e.loaded / e.total) * 100 * numbers.PROGRESS_COEFFICIENT).toFixed(0)) || 0;
  447. }
  448. const index = this._getFileIndex(fileInstance, newFileList);
  449. if (index < 0) {
  450. return;
  451. }
  452. newFileList[index].percent = percent;
  453. newFileList[index].status = FILE_STATUS_UPLOADING;
  454. this._adapter.notifyProgress(percent, fileInstance, newFileList);
  455. this._adapter.updateFileList(newFileList);
  456. this._adapter.notifyChange({ fileList: newFileList, currentFile: newFileList[index] });
  457. }
  458. handleOnLoad({ e, xhr, fileInstance }: { e: ProgressEvent; xhr: XMLHttpRequest; fileInstance: File }): void {
  459. const { fileList } = this.getStates();
  460. const index = this._getFileIndex(fileInstance, fileList);
  461. if (index < 0) {
  462. return;
  463. }
  464. if (xhr.status < 200 || xhr.status >= 300) {
  465. this.handleError({ e, xhr, fileInstance });
  466. } else {
  467. this.handleSuccess({ e, xhr, fileInstance, index } as any);
  468. }
  469. }
  470. handleSuccess({ e, fileInstance, isCustomRequest = false, xhr, response }: { e: ProgressEvent; fileInstance: CustomFile; isCustomRequest?: boolean; xhr?: XMLHttpRequest; response?: any }): void {
  471. const { fileList } = this.getStates();
  472. let body: any = null;
  473. const index = this._getFileIndex(fileInstance, fileList);
  474. if (index < 0) {
  475. return;
  476. }
  477. if (isCustomRequest) {
  478. // use when pass customRequest
  479. body = response;
  480. } else {
  481. body = this.getBody(xhr);
  482. }
  483. const newFileList = fileList.slice();
  484. const { afterUpload } = this.getProps();
  485. newFileList[index].status = FILE_STATUS_SUCCESS;
  486. newFileList[index].percent = 100;
  487. this._adapter.notifyProgress(100, fileInstance, newFileList);
  488. newFileList[index].response = body;
  489. e ? (newFileList[index].event = e) : null;
  490. if (afterUpload && typeof afterUpload === 'function') {
  491. const { autoRemove, status, validateMessage, name } =
  492. this._adapter.notifyAfterUpload({
  493. response: body,
  494. file: newFileList[index],
  495. fileList: newFileList,
  496. }) || {};
  497. status ? (newFileList[index].status = status) : null;
  498. validateMessage ? (newFileList[index].validateMessage = validateMessage) : null;
  499. name ? (newFileList[index].name = name) : null;
  500. autoRemove ? newFileList.splice(index, 1) : null;
  501. }
  502. this._adapter.notifySuccess(body, fileInstance, newFileList);
  503. this._adapter.notifyChange({ fileList: newFileList, currentFile: newFileList[index] });
  504. this._adapter.updateFileList(newFileList);
  505. }
  506. _getFileIndex(file: CustomFile | BaseFileItem, fileList: Array<BaseFileItem>): number {
  507. return fileList.findIndex(item => item.uid === file.uid);
  508. }
  509. handleRemove(file: BaseFileItem): void {
  510. const { disabled } = this.getProps();
  511. if (disabled) {
  512. return;
  513. }
  514. const { fileList } = this.getStates();
  515. Promise.resolve(this._adapter.notifyBeforeRemove(file, fileList)).then(res => {
  516. // prevent remove while user return false
  517. if (res === false) {
  518. return;
  519. }
  520. const newFileList = fileList.slice();
  521. const index = this._getFileIndex(file, fileList);
  522. if (index < 0) {
  523. return;
  524. }
  525. newFileList.splice(index, 1);
  526. this._adapter.notifyRemove(file.fileInstance, newFileList, file);
  527. this._adapter.updateFileList(newFileList);
  528. this._adapter.notifyChange({ fileList: newFileList, currentFile: file });
  529. });
  530. }
  531. handleError({ e, xhr, fileInstance }: { e: ProgressEvent;xhr: XMLHttpRequest;fileInstance: CustomFile }): void {
  532. const { fileList } = this.getStates();
  533. const index = this._getFileIndex(fileInstance, fileList);
  534. if (index < 0) {
  535. return;
  536. }
  537. const { action } = this.getProps();
  538. const newFileList = fileList.slice();
  539. const error = this.getError({ action, xhr, fileName: fileInstance.name });
  540. newFileList[index].status = FILE_STATUS_UPLOAD_FAIL;
  541. newFileList[index].response = error;
  542. newFileList[index].event = e;
  543. this._adapter.notifyError(error, fileInstance, newFileList, xhr);
  544. this._adapter.updateFileList(newFileList);
  545. this._adapter.notifyChange({ currentFile: newFileList[index], fileList: newFileList });
  546. }
  547. handleClear() {
  548. const { disabled } = this.getProps();
  549. const { fileList } = this.getStates();
  550. if (disabled) {
  551. return;
  552. }
  553. Promise.resolve(this._adapter.notifyBeforeClear(fileList)).then(res => {
  554. if (res === false) {
  555. return;
  556. }
  557. this._adapter.updateFileList([]);
  558. this._adapter.notifyClear();
  559. this._adapter.notifyChange({ fileList: [] } as any);
  560. });
  561. }
  562. _createURL(fileInstance: CustomFile): string {
  563. // https://stackoverflow.com/questions/31742072/filereader-vs-window-url-createobjecturl
  564. const url = URL.createObjectURL(fileInstance);
  565. const { localUrls } = this.getStates();
  566. const newUrls = localUrls.slice();
  567. newUrls.push(url);
  568. this._adapter.updateLocalUrls(newUrls);
  569. return url;
  570. }
  571. // 释放预览文件所占用的内存
  572. // Release memory used by preview files
  573. releaseMemory(): void {
  574. const { localUrls }: { localUrls: Array<string> } = this.getStates();
  575. localUrls.forEach(url => {
  576. this._releaseBlob(url);
  577. });
  578. }
  579. _releaseBlob(url: string): void {
  580. try {
  581. URL.revokeObjectURL(url);
  582. } catch (error) {
  583. console.log(error);
  584. }
  585. }
  586. isImage(file: CustomFile): boolean {
  587. return /(webp|svg|png|gif|jpg|jpeg|bmp|dpg)$/i.test(file.type);
  588. }
  589. isMultiple(): boolean {
  590. return Boolean(this.getProp('multiple'));
  591. }
  592. _dragEnterTarget: EventTarget;
  593. handleDragEnter(e: any): void {
  594. e.preventDefault();
  595. e.stopPropagation();
  596. this._dragEnterTarget = e.currentTarget;
  597. const { disabled } = this.getProps();
  598. if (!disabled) {
  599. this._adapter.updateDragAreaStatus(DRAG_AREA_LEGAL);
  600. }
  601. }
  602. async handleDirectoryDrop(e: any): Promise<void> {
  603. const fileList = this.getState('fileList').slice();
  604. const items = [].slice.call(e.dataTransfer.items);
  605. const files = await mapFileTree(items);
  606. this.handleChange(files);
  607. this._adapter.updateDragAreaStatus(DRAG_AREA_DEFAULT);
  608. this._adapter.notifyDrop(e, files, fileList);
  609. }
  610. handleDrop(e: any): void {
  611. // Block file opening in browser
  612. e.preventDefault();
  613. e.stopPropagation();
  614. const { disabled, directory } = this.getProps();
  615. const fileList = this.getState('fileList').slice();
  616. if (!disabled) {
  617. if (directory) {
  618. this.handleDirectoryDrop(e);
  619. }
  620. const files: File[] = Array.from(e.dataTransfer.files);
  621. this.handleChange(files);
  622. this._adapter.updateDragAreaStatus(DRAG_AREA_DEFAULT);
  623. this._adapter.notifyDrop(e, files, fileList);
  624. }
  625. }
  626. handleDragOver(e: any): void {
  627. e.preventDefault();
  628. e.stopPropagation();
  629. }
  630. handleDragLeave(e: any): void {
  631. e.preventDefault();
  632. e.stopPropagation();
  633. // 防止拖拽进入子元素时触发的dragLeave也被处理
  634. // Prevent dragLeave triggered when dragging into a child element is also handled
  635. // https://stackoverflow.com/questions/7110353/html5-dragleave-fired-when-hovering-a-child-element
  636. if (this._dragEnterTarget === e.target) {
  637. this._adapter.updateDragAreaStatus(DRAG_AREA_DEFAULT);
  638. }
  639. }
  640. // 拖拽上传时,需要对文件的格式进行校验
  641. // When dragging and uploading, you need to verify the file format
  642. checkFileFormat(accept: string, file: File): boolean {
  643. const acceptTypes = accept
  644. .split(',')
  645. .map(type => type.trim())
  646. .filter(type => type);
  647. const mimeType = file.type || '';
  648. // Get the large class to which MIMEtype belongs, eg: image/jpeg = > image, application/= > application
  649. const baseMimeType = mimeType.replace(/\/.*$/, '');
  650. return acceptTypes.some(type => {
  651. // When accepted as a suffix filename such as [.jpeg]
  652. if (type.charAt(0) === '.') {
  653. const fileName = file.name || '';
  654. const acceptExtension = type.split('.').pop().toLowerCase();
  655. return endsWith(fileName.toLowerCase(), acceptExtension);
  656. }
  657. // When accepted as a general class such as [image/*] or [video/*]
  658. if (/\/\*$/.test(type)) {
  659. const acceptBaseMimeType = type.replace(/\/.*$/, '');
  660. return baseMimeType === acceptBaseMimeType;
  661. }
  662. // When accepted as a full MIME types string
  663. if (/^[^\/]+\/[^\/]+$/.test(type)) {
  664. return mimeType === type;
  665. }
  666. return false;
  667. });
  668. }
  669. retry(fileItem: BaseFileItem): void {
  670. const { onRetry } = this.getProps();
  671. if (onRetry && typeof onRetry === 'function') {
  672. onRetry(fileItem);
  673. }
  674. this.post(fileItem);
  675. }
  676. handlePreviewClick(fileItem: BaseFileItem): void {
  677. this._adapter.notifyPreviewClick(fileItem);
  678. }
  679. }
  680. export default UploadFoundation;