import React from "react"; import { Upload, Icon, Modal, message } from "antd"; import dayjs from "dayjs"; import shortid from "shortid"; import { OSS_ENDPOINT, OSS_BUCKET, DRIVER_LICENSE_PATH, ERROR_DEFAULT, MAX_UPLOAD_NUMBER } from "../../constant"; import Comment from "../../Comment"; // import styles from "./Upload.less"; import "./Upload.css"; const client = oss => { return new window.OSS.Wrapper({ accessKeyId: oss.access_key_id, accessKeySecret: oss.access_key_secret, stsToken: oss.security_token, endpoint: OSS_ENDPOINT, //常量,你可以自己定义 bucket: OSS_BUCKET }); }; const uploadPath = (path, file) => { return `${path}/${dayjs().format("YYYYMMDD")}/${shortid.generate()}.${ file.type.split("/")[1] }`; }; const UploadToOss = (oss, path, file) => { const url = uploadPath(path, file); return new Promise((resolve, reject) => { client(oss) .multipartUpload(url, file) .then(data => { resolve(data); }) .catch(error => { reject(error); }); }); }; class App extends React.Component { constructor(props) { super(props); this.state = { previewVisible: false, previewImage: "" }; this.handleCancel = this.handleCancel.bind(this); this.handlePreview = this.handlePreview.bind(this); this.handleChange = this.handleChange.bind(this); this.customRequest = this.customRequest.bind(this); } componentDidMount() { this.props.app.sOssSts(); } handleCancel() { this.setState({ previewVisible: false }); } handlePreview(file) { this.setState({ previewImage: file.url || file.thumbUrl, previewVisible: true }); } handleChange({ fileList }) { this.props.onChangeFileList(fileList); } customRequest(info) { const { file } = info; info.onProgress({ percent: 10 }); let reader = new FileReader(); reader.readAsDataURL(info.file); reader.onloadend = () => { info.onProgress({ percent: 20 }); // DRIVER_LICENSE_PATH oss 的存储路径位置 UploadToOss(this.props.app.oss, DRIVER_LICENSE_PATH, file) .then(data => { info.onProgress({ percent: 100 }); info.onSuccess(); this.props.onUpload({ path: data.name, uid: file.uid }); }) .catch(e => { message.error(e.message || ERROR_DEFAULT); info.onError(e); }); }; } render() { const { previewVisible, previewImage } = this.state; const { fileList } = this.props; const uploadButton = (
上传
); return (
{fileList.length >= MAX_UPLOAD_NUMBER ? null : uploadButton} upload
); } } export default Comment(App);