ant-design/components/upload/Upload.tsx

376 lines
9.2 KiB
TypeScript
Raw Normal View History

import * as React from 'react';
import { polyfill } from 'react-lifecycles-compat';
import RcUpload from 'rc-upload';
import classNames from 'classnames';
2018-03-08 13:36:12 +08:00
import uniqBy from 'lodash/uniqBy';
import findIndex from 'lodash/findIndex';
import Dragger from './Dragger';
import UploadList from './UploadList';
import {
RcFile,
UploadProps,
UploadState,
UploadFile,
UploadLocale,
UploadChangeParam,
UploadType,
UploadListType,
} from './interface';
import { T, fileToObject, genPercentAdd, getFileItem, removeFileItem } from './utils';
import LocaleReceiver from '../locale-provider/LocaleReceiver';
import defaultLocale from '../locale/default';
import { ConfigConsumer, ConfigConsumerProps } from '../config-provider';
import warning from '../_util/warning';
export { UploadProps };
class Upload extends React.Component<UploadProps, UploadState> {
static Dragger: typeof Dragger;
static defaultProps = {
type: 'select' as UploadType,
multiple: false,
action: '',
data: {},
accept: '',
beforeUpload: T,
showUploadList: true,
listType: 'text' as UploadListType, // or picture
className: '',
disabled: false,
supportServerRender: true,
};
static getDerivedStateFromProps(nextProps: UploadProps) {
if ('fileList' in nextProps) {
return {
fileList: nextProps.fileList || [],
};
}
return null;
}
recentUploadStatus: boolean | PromiseLike<any>;
2019-01-11 17:20:48 +08:00
progressTimer: any;
upload: any;
2017-11-20 16:31:41 +08:00
constructor(props: UploadProps) {
super(props);
2017-11-10 09:47:30 +08:00
this.state = {
2017-11-10 09:47:30 +08:00
fileList: props.fileList || props.defaultFileList || [],
dragState: 'drop',
};
warning(
'fileList' in props || !('value' in props),
'Upload',
'`value` is not validate prop, do you mean `fileList`?',
);
}
componentWillUnmount() {
this.clearProgressTimer();
}
2019-08-05 18:38:10 +08:00
saveUpload = (node: typeof RcUpload) => {
this.upload = node;
};
onStart = (file: RcFile) => {
2019-08-05 18:38:10 +08:00
const { fileList } = this.state;
const targetItem = fileToObject(file);
2017-11-20 16:53:56 +08:00
targetItem.status = 'uploading';
2019-08-05 18:38:10 +08:00
const nextFileList = fileList.concat();
const fileIndex = findIndex(nextFileList, ({ uid }: UploadFile) => uid === targetItem.uid);
if (fileIndex === -1) {
nextFileList.push(targetItem);
} else {
nextFileList[fileIndex] = targetItem;
}
this.onChange({
file: targetItem,
fileList: nextFileList,
});
// fix ie progress
if (!(window as any).FormData) {
this.autoUpdateProgress(0, targetItem);
}
2018-12-07 20:02:01 +08:00
};
2017-11-20 16:31:41 +08:00
onSuccess = (response: any, file: UploadFile) => {
this.clearProgressTimer();
try {
if (typeof response === 'string') {
response = JSON.parse(response);
}
2018-12-07 20:02:01 +08:00
} catch (e) {
/* do nothing */
}
2019-08-05 18:38:10 +08:00
const { fileList } = this.state;
2018-11-10 21:40:21 +08:00
const targetItem = getFileItem(file, fileList);
// removed
if (!targetItem) {
return;
}
targetItem.status = 'done';
targetItem.response = response;
this.onChange({
file: { ...targetItem },
fileList,
});
2018-12-07 20:02:01 +08:00
};
2017-11-20 16:31:41 +08:00
onProgress = (e: { percent: number }, file: UploadFile) => {
2019-08-05 18:38:10 +08:00
const { fileList } = this.state;
2018-11-10 21:40:21 +08:00
const targetItem = getFileItem(file, fileList);
// removed
if (!targetItem) {
return;
}
targetItem.percent = e.percent;
this.onChange({
event: e,
file: { ...targetItem },
2019-08-05 18:38:10 +08:00
fileList,
});
2018-12-07 20:02:01 +08:00
};
2017-11-20 16:31:41 +08:00
onError = (error: Error, response: any, file: UploadFile) => {
this.clearProgressTimer();
2019-08-05 18:38:10 +08:00
const { fileList } = this.state;
2018-11-10 21:40:21 +08:00
const targetItem = getFileItem(file, fileList);
// removed
if (!targetItem) {
return;
}
targetItem.error = error;
targetItem.response = response;
targetItem.status = 'error';
this.onChange({
file: { ...targetItem },
fileList,
});
2018-12-07 20:02:01 +08:00
};
2017-11-20 16:31:41 +08:00
handleManualRemove = (file: UploadFile) => {
if (this.upload) {
this.upload.abort(file);
}
this.handleRemove(file);
2018-12-07 20:02:01 +08:00
};
onChange = (info: UploadChangeParam) => {
if (!('fileList' in this.props)) {
this.setState({ fileList: info.fileList });
}
const { onChange } = this.props;
if (onChange) {
onChange(info);
}
2018-12-07 20:02:01 +08:00
};
2017-11-20 16:31:41 +08:00
onFileDrop = (e: React.DragEvent<HTMLDivElement>) => {
this.setState({
dragState: e.type,
});
2018-12-07 20:02:01 +08:00
};
beforeUpload = (file: RcFile, fileList: RcFile[]) => {
2019-08-05 18:38:10 +08:00
const { beforeUpload } = this.props;
const { fileList: stateFileList } = this.state;
if (!beforeUpload) {
return true;
}
2019-08-05 18:38:10 +08:00
const result = beforeUpload(file, fileList);
if (result === false) {
this.onChange({
file,
fileList: uniqBy(
2019-08-05 18:38:10 +08:00
stateFileList.concat(fileList.map(fileToObject)),
(item: UploadFile) => item.uid,
),
});
return false;
2019-01-11 17:20:48 +08:00
}
if (result && (result as PromiseLike<any>).then) {
return result;
}
return true;
2018-12-07 20:02:01 +08:00
};
2019-08-05 18:38:10 +08:00
handleRemove(file: UploadFile) {
const { onRemove } = this.props;
const { fileList } = this.state;
const { status } = file;
file.status = 'removed'; // eslint-disable-line
Promise.resolve(typeof onRemove === 'function' ? onRemove(file) : onRemove).then(ret => {
// Prevent removing file
if (ret === false) {
file.status = status;
return;
}
const removedFileList = removeFileItem(file, fileList);
if (removedFileList) {
this.onChange({
file,
fileList: removedFileList,
});
}
});
}
clearProgressTimer() {
clearInterval(this.progressTimer);
}
2019-08-05 18:38:10 +08:00
autoUpdateProgress(_: any, file: UploadFile) {
const getPercent = genPercentAdd();
let curPercent = 0;
this.clearProgressTimer();
this.progressTimer = setInterval(() => {
curPercent = getPercent(curPercent);
this.onProgress(
{
percent: curPercent * 100,
},
file,
);
}, 200);
}
2017-11-20 16:31:41 +08:00
renderUploadList = (locale: UploadLocale) => {
2019-08-05 18:38:10 +08:00
const {
showUploadList,
listType,
onPreview,
previewFile,
disabled,
locale: propLocale,
} = this.props;
const { showRemoveIcon, showPreviewIcon } = showUploadList as any;
2019-08-05 18:38:10 +08:00
const { fileList } = this.state;
return (
<UploadList
listType={listType}
2019-08-05 18:38:10 +08:00
items={fileList}
meger feature to master (#16421) * use ul in list * update snapshot * update comment * feat: TreeSelect support `showSearch` in multiple mode (#15933) * update rc-tree-select * typo * update desc & snapshot * update desc & snapshot * check default showSearch * feat: table customizing variable (#15971) * feat: added table selected row color variable * fix: @table-selected-row-color default is inherit * feat: Upload support customize previewFile (#15984) * support preview file * use promise * dealy load * use canvas of render * use domHook of test * update demo * add snapshot * update types * update testcase * feat: form customizing variables (#15954) * fix: added styling form input background-color * feat: added '@form-warning-input-bg' variable * feat: added '@form-error-input-bg' variable * use li wrap with comment * feat: Support append theme less file with less-variable (#16118) * add override * add override support * update doc * feat: dropdown support set right icon * docs: update doc of dropdown component * style: format dropdown-button.md * test: update updateSnapshot * style: format dropdown-button.md * test: update updateSnapshot * test: update updateSnapshot * style: change style of dropdown-button demo * fix: fix document table order * feat: Support SkeletonAvatarProps.size accept number (#16078) (#16128) * chore:update style of demo * feat: Notification functions accept top, bottom and getContainer as arguments * drawer: add afterVisibleChange * rm onVisibleChange * update * feat: 🇭🇷 hr_HR locale (#16258) * Added Croatian locale * fixed lint error * :white_check_mark: Add test cases for hr_HR * :memo: update i18n documentation * feat: add `htmlFor` in Form.Item (#16278) * add htmlFor in Form.Item * update doc * feat: Button support `link` type (#16289) close #15892 * feat: Add Timeline.Item.position (#16148) (#16193) * fix: Timeline.pendingDot interface documentation there is a small problem (#16177) * feat: Add Timeline.Item.position (#16148) * doc: add version infomation for Timeline.Item.position * refactor: Update Tree & TreeSelect deps (#16330) * use CSSMotion * update snapshot * feat: Collapse support `expandIconPosition` (#16365) * update doc * support expandIconPosition * update snapshot * feat: Breadcrumb support DropDown (#16315) * breadcrumbs support drop down menu * update doc * add require less * fix test * fix md doc * less code * fix style warning * update snap * add children render test * feat: TreeNode support checkable * feat: add optional to support top and left slick dots (#16186) (#16225) * add optional to support top and left slick dots * update carousel snapshot * Update doc, add placement demo * update carousel placement demo snapshots * rename dots placement to position * update vertical as deprecated * rename dotsPosition to dotPosition * refine code * add warning testcase for vertical * remove unused warning * update expression * Additional test case for dotPosition * refactor: Upgrade `rc-tree-select` to support pure React motion (#16402) * upgrade `rc-tree-select` * update snapshot * 3.17.0 changelog * fix warning * fix review warning
2019-05-06 12:04:39 +08:00
previewFile={previewFile}
onPreview={onPreview}
onRemove={this.handleManualRemove}
2019-05-25 16:34:38 +08:00
showRemoveIcon={!disabled && showRemoveIcon}
showPreviewIcon={showPreviewIcon}
2019-08-05 18:38:10 +08:00
locale={{ ...locale, ...propLocale }}
/>
);
2018-12-07 20:02:01 +08:00
};
renderUpload = ({ getPrefixCls }: ConfigConsumerProps) => {
const {
prefixCls: customizePrefixCls,
className,
showUploadList,
listType,
type,
disabled,
children,
} = this.props;
2019-08-05 18:38:10 +08:00
const { fileList, dragState } = this.state;
const prefixCls = getPrefixCls('upload', customizePrefixCls);
const rcUploadProps = {
onStart: this.onStart,
onError: this.onError,
onProgress: this.onProgress,
onSuccess: this.onSuccess,
...this.props,
prefixCls,
beforeUpload: this.beforeUpload,
};
delete rcUploadProps.className;
const uploadList = showUploadList ? (
2018-12-07 20:02:01 +08:00
<LocaleReceiver componentName="Upload" defaultLocale={defaultLocale.Upload}>
{this.renderUploadList}
</LocaleReceiver>
) : null;
if (type === 'drag') {
const dragCls = classNames(prefixCls, {
[`${prefixCls}-drag`]: true,
2019-08-05 18:38:10 +08:00
[`${prefixCls}-drag-uploading`]: fileList.some(file => file.status === 'uploading'),
[`${prefixCls}-drag-hover`]: dragState === 'dragover',
[`${prefixCls}-disabled`]: disabled,
});
return (
<span className={className}>
<div
className={dragCls}
onDrop={this.onFileDrop}
onDragOver={this.onFileDrop}
onDragLeave={this.onFileDrop}
>
<RcUpload {...rcUploadProps} ref={this.saveUpload} className={`${prefixCls}-btn`}>
2018-12-07 20:02:01 +08:00
<div className={`${prefixCls}-drag-container`}>{children}</div>
</RcUpload>
</div>
{uploadList}
</span>
);
}
const uploadButtonCls = classNames(prefixCls, {
[`${prefixCls}-select`]: true,
[`${prefixCls}-select-${listType}`]: true,
[`${prefixCls}-disabled`]: disabled,
});
// Remove id to avoid open by label when trigger is hidden
// https://github.com/ant-design/ant-design/issues/14298
// https://github.com/ant-design/ant-design/issues/16478
if (!children || disabled) {
delete rcUploadProps.id;
}
const uploadButton = (
<div className={uploadButtonCls} style={children ? undefined : { display: 'none' }}>
<RcUpload {...rcUploadProps} ref={this.saveUpload} />
</div>
);
if (listType === 'picture-card') {
return (
2019-07-22 19:18:47 +08:00
<span className={classNames(className, `${prefixCls}-picture-card-wrapper`)}>
{uploadList}
{uploadButton}
</span>
);
}
2019-07-22 19:18:47 +08:00
return (
<span className={className}>
{uploadButton}
{uploadList}
</span>
);
2018-12-07 20:02:01 +08:00
};
render() {
2018-12-07 20:02:01 +08:00
return <ConfigConsumer>{this.renderUpload}</ConfigConsumer>;
}
}
polyfill(Upload);
export default Upload;