import React from 'react'; import { Upload, message, Button } from 'antd'; class AliyunOSSUpload extends React.Component { state = { OSSData: {}, }; componentDidMount() { this.init(); } init = () => { try { const { OSSData } = this.props; this.setState({ OSSData, }); } catch (error) { message.error(error); } }; onChange = ({ file, fileList }) => { const { onChange, onDone, onUploading } = this.props; console.log('Aliyun OSS:', file, fileList); if (onChange) { onChange([...fileList]); } if (onDone) { if (file.status === 'done') onDone(file); } if (onUploading && file.status === 'uploading') { onUploading({ file, fileList }); } this.setState({ fileList: [...fileList] }); }; onRemove = file => { const { value, onChange } = this.props; const files = value.filter(v => v.url !== file.url); if (onChange) { onChange(files); } }; transformFile = file => { const { OSSData } = this.state; file.url = OSSData.dir + '/' + file.name; return file; }; getExtraData = file => { const { OSSData } = this.state; return { key: file.url, OSSAccessKeyId: OSSData.accessid, policy: OSSData.policy, Signature: OSSData.signature, }; }; beforeUpload = async file => { const { OSSData } = this.state; const expire = OSSData.expire * 1000; file.url = OSSData.dir + '/' + file.name; console.log(file); if (expire < Date.now()) { await this.init(); } if (this.props.beforeUpload) { return this.props.beforeUpload(file); } return true; }; render() { const { value, directory, label, noStyle, showUploadList, accept } = this.props; const props = { name: 'file', fileList: this.state.fileList, action: this.state.OSSData.host, onChange: this.onChange, onRemove: this.onRemove, transformFile: this.transformFile, data: this.getExtraData, beforeUpload: this.beforeUpload, accept: accept, showUploadList: showUploadList !== false, headers: { 'Access-Control-Allow-Origin': '*' }, }; return ( {noStyle ? label : } ); } } export default AliyunOSSUpload;