foundation.ts 35 KB

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