UploadCom.js 7.3 KB
Newer Older
1
// 图片上传组件
2
import React from 'react';
3
import { Button, Icon, message, Upload } from 'antd';
4
import { queryApiActionPath } from '../utils/queryConfig';
5 6 7
import config from '@/webPublic/one_stop_public/config';
import styles from './style.less';
import UploadComDiyForQnZy from '@/webPublic/one_stop_public/libs/UploadComDiyForQnZy';
8
import Viewer from 'react-viewer';
9
import { getToken } from '@/webPublic/one_stop_public/utils/token';
徐立's avatar
徐立 committed
10

11
message.config({
12 13
	top: 300,
});
14

15
export function checkIsImage(path) {
16 17 18
	if (!path) {
		return false;
	}
19 20 21
	if(typeof path !== 'string'){
	  return false;
  }
22 23 24 25 26
	let p = path.toLowerCase();
	let find = ['.jpg', '.png', '.jpeg', '.bmp', '.gif', '.bmp', '.svg'].find((x) => {
		return path.indexOf(x) > -1;
	});
	return !!find;
27 28
}

29
export default function index(props) {
钟是志's avatar
钟是志 committed
30
	if (window.specialImportantSystemConfig && window.specialImportantSystemConfig.schoolName === '黔南民族职业技术学院' && window.location.href.indexOf('jy/geren/subsidy') > -1) {
31 32 33 34
		return <UploadComDiyForQnZy {...props} />;
	} else {
		return <UploadCom {...props} />;
	}
35 36
}

37 38 39 40 41 42 43 44 45 46 47 48 49
/**
 *
 * otherProps: {
 *   limitImageSize: {
 *     width:  number// 限制上传的图片的最小宽度
 *     height: number// 限制上传的图片的最小高度
 *     widthMinusHeight: number// 限制必须宽度大于高度 且 宽度 - 高度 >= widthMinusHeight
 *   }
 *   limitWarnningMessage: string// 当图片不满足限制条件时 提示语句
 *   limitImageInfo: string// 在上传按钮旁展示的提示语句
 * }
 * */

50
class UploadCom extends React.Component {
51 52 53 54 55 56 57 58 59 60 61 62 63 64
	constructor(props) {
		super(props);
		const value = props.value || {};
		this.state = {
			files: value.files,
			previewVisible: false,
			previewImage: '',
		};
		this.otherProps = {};
		if (props.json?.otherProps) {
			this.otherProps = props.json?.otherProps;
			try {
				this.otherProps = new Function(this.otherProps)();
				// console.log(this.otherProps);
65 66 67
			} catch (e) {
			  console.log(e);
      }
68 69
		}
	}
70

71 72 73 74 75 76 77
	triggerChange = (changedValue) => {
		// Should provide an event to pass value to Form.
		const onChange = this.props.onChange;
		if (onChange) {
			onChange(Object.assign({}, this.state, changedValue));
		}
	};
78

79 80
	//图片上传之前进行判断
	beforeUpload = (file) => {
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
	  const { limitImageSize, onlyPdf } = this.otherProps;
	  if(limitImageSize){ // 限制上传图片大小
      return this.isSize(file).then((res) => {
        message.info('正在上传中,请等待');
        return true;
      });
    }else if(onlyPdf){ // 限制只能上传pdf文件
	    let name = file.name;
	    if(!name || !name.endsWith('.pdf')){
	      message.warn('请上传pdf文件');
	      return false;
      }
    }
	  return true;

96
	};
97

98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
	//检测尺寸
	isSize = (file) => {
		const { limitWarnningMessage } = this.otherProps;
		return new Promise((resolve, reject) => {
			let { width, height, widthMinusHeight } = this.otherProps.limitImageSize;
			let _URL = window.URL || window.webkitURL;
			let img = new Image();
			img.onload = function() {
				let valid = img.width >= width && img.height >= height;
				if (!!widthMinusHeight && valid) {
					if (widthMinusHeight > 0) {
						if (img.width - img.height < widthMinusHeight) {
							// widthMinusHeight: number// 限制必须宽度大于高度 且 宽度 - 高度 >= widthMinusHeight
							valid = false;
						}
					}
					if (widthMinusHeight < 0) {
						if (img.height - img.width < Math.abs(widthMinusHeight)) {
							// widthMinusHeight: number// 限制必须高度大于宽度
							valid = false;
						}
					}
				}
				valid ? resolve() : reject();
			};
			img.src = _URL.createObjectURL(file);
		}).then(
			() => {
				return file;
			},
			() => {
				message.error(file.name + limitWarnningMessage);
				return Promise.reject();
			},
		);
	};
134

135 136 137 138 139 140 141
	componentWillReceiveProps(nextProps) {
		// Should be a controlled component.
		if ('value' in nextProps) {
			const value = nextProps.value;
			this.setState(value);
		}
	}
142

143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
	changeUrl = (info) => {
		if (info.file.status === 'done') {
			message.success(`${info.file.name} 上传成功`);
			const files = this.state.files;
			files.push({ path: info.file.response, name: info.file.name });
			if (!('value' in this.props)) {
				this.setState({ files });
			}
			this.triggerChange({ files });
		} else if (info.file.status === 'error') {
			message.error(`${info.file.name} 上传失败`);
		}
	};
	remove = (path) => {
		const files = this.state.files;
		for (var i = 0; i < files.length; i++) {
			if (files[i].path == path) {
				files.splice(i, 1);
				break;
			}
		}
		if (!('value' in this.props)) {
			this.setState({ files });
		}
		this.triggerChange({ files });
	};
169

170
	render() {
171
	  // console.log(this.props.value);
172
		const { files, previewVisible, previewImage, previewImageName } = this.state;
钟是志's avatar
钟是志 committed
173
		const { isMultiple, accept, btnName, disabled, dataKey } = this.props;
174 175 176 177
		const props = {
			name: 'file',
			multiple: isMultiple,
			accept: accept,
178 179 180 181 182 183
      headers: {
        Authorization: `bearer ${getToken()}`,
      },
      data: {
        token: getToken(),
      },
184 185 186
			action: config.uploadUrl,
			showUploadList: false,
			onChange: this.changeUrl,
187 188
      // beforeUpload: this.otherProps?.limitImageSize ? this.beforeUpload : undefined,
      beforeUpload: this.beforeUpload
189 190
		};
		return (
钟是志's avatar
钟是志 committed
191
			<div data-mes={dataKey}>
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
				{' '}
				<Upload {...props} disabled={disabled}>
					{!disabled && (
						<>
							<Button>
								<Icon type="upload" />
								{btnName ? btnName : '上传附件'}
							</Button>
							{this.otherProps?.limitImageInfo && <div>{this.otherProps?.limitImageInfo}</div>}
						</>
					)}
				</Upload>
				<ul className={styles.ulImageList}>
					{((Array.isArray(files) && files) || []).map((f) => {
					  // console.log(f);
						if (f.path && checkIsImage(f.path)) {
							return (
								<li key={f.path} className={styles.preview_img}>
									<div className={styles.preview_div}>
										<img
											style={{ width: '100px', height: 'auto' }}
											className={styles.img}
											src={queryApiActionPath() + f.path}
										/>
										<div
											className={styles.mask}
											onClick={() => {
												// window.open(queryApiActionPath() + f.path);
												this.setState({
													previewImage: queryApiActionPath() + f.path,
                          previewImageName : f.name,
223 224
                          previewVisible: true,
                        });
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
											}}>
											<Icon type="eye" className={styles.icon_eye} />
										</div>
									</div>
									{!disabled && (
										<Icon
											style={{ marginLeft: 10 }}
											type="delete"
											onClick={this.remove.bind(this, f.path)}
										/>
									)}
								</li>
							);
						}
						return (
							<li key={f.path}>
								<a target="_blank" key={f.path} href={queryApiActionPath() + f.path}>
									{f.name}
								</a>{' '}
								{!disabled && (
									<Icon
										style={{ marginLeft: 10 }}
										type="delete"
										onClick={this.remove.bind(this, f.path)}
									/>
								)}
							</li>
						);
					})}
				</ul>
					<Viewer
						visible={previewVisible}
						onClose={() => {
							this.setState({ previewVisible: false });
						}}
						images={[
							{
								src: previewImage,
								alt: previewImageName,
							},
						]}
					/>
			</div>
		);
	}
徐立's avatar
徐立 committed
270
}