123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107 |
- 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 (
- <Upload {...props} directory={directory}>
- {noStyle ? label : <Button type="primary">{label}</Button>}
- </Upload>
- );
- }
- }
- export default AliyunOSSUpload;
|