plot-plan-designer
Version:
Design Editor Tools with React.js + ant.design + fabric.js
89 lines (88 loc) • 3.2 kB
JavaScript
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { InboxOutlined } from '@ant-design/icons';
import { Upload, message } from 'antd';
import { supportedFileType } from './utils/utils';
const { Dragger } = Upload;
import i18n from 'i18next';
class FileUpload extends Component {
constructor(props) {
super(props);
this.state = {
fileList: this.props.value ? [this.props.value] : [],
};
//this func help to bind error to show up in parent component if has
this.processErr = (error) => {
const { bindError } = this.props;
bindError ? bindError(error) : message.error(error);
return false;
};
}
UNSAFE_componentWillReceiveProps(nextProps) {
this.setState({
fileList: nextProps.value ? [nextProps.value] : [],
});
}
render() {
const { accept, limit, onChange } = this.props;
const { fileList } = this.state;
const props = {
accept,
name: 'file',
multiple: false,
onChange: (info) => {
const isLimit = info.file.size / 1024 / 1024 < limit;
if (!isLimit) {
return this.processErr(`Limited to ${limit}MB or less`);
}
if (!supportedFileType(info.file)) {
return this.processErr('Only accept image or pdf type, please choose another file.');
}
onChange(info.file);
},
onRemove: (file) => {
this.setState(({ fileList }) => {
const index = fileList.indexOf(file);
const newFileList = fileList.slice();
newFileList.splice(index, 1);
return {
fileList: newFileList,
};
}, () => {
const { onChange } = this.props;
onChange(null);
});
},
beforeUpload: (file) => {
const isLimit = file.size / 1024 / 1024 < limit;
if (!isLimit) {
return false;
}
if (!supportedFileType(file)) {
return false;
}
this.setState({
fileList: [file],
});
return false;
},
fileList,
};
return (React.createElement(Dragger, Object.assign({}, props),
React.createElement("p", { className: "ant-upload-drag-icon" },
React.createElement(InboxOutlined, null)),
React.createElement("p", { className: "ant-upload-text" }, i18n.t('common.file-upload')),
React.createElement("p", { className: "ant-upload-hint" }, i18n.t('common.file-upload-desc', { limit: limit }))));
}
}
FileUpload.propTypes = {
onChange: PropTypes.func,
limit: PropTypes.number,
accept: PropTypes.string,
value: PropTypes.any,
bindError: PropTypes.func,
};
FileUpload.defaultProps = {
limit: 5,
};
export default FileUpload;