1.创建一个上传Upload组件
import React from 'react';
import { Upload, Icon, Modal } from 'antd';
import { isImage } from '../../utils/tool';
class UploadFile extends React.Component {
constructor(props) {
super(props);
this.state.imageUrl = props.imageUrl;
this.state.type = props.type;
}
state = {
imageUrl: '',
type: '',
previewVisible: false,
fileList: []
}
handleChange = info => {
if (info.file.status === 'uploading') {
this.setState({ loading: true });
return;
}
if (info.file.status === 'done') {
//返回服务器路径和文件名
this.props.imageChange(info.file.response.result,info.file.name)
this.setState({
loading: false,
})
}
};
static getDerivedStateFromProps(newProps, oldProps) {
if (newProps.imageUrl !== oldProps.imageUrl) {
return {
...oldProps,
imageUrl: newProps.imageUrl,
type: newProps.type,
}
}
return null;
}
handleCancel = () => this.setState({ previewVisible: false });
handlePreview = e => {
e.stopPropagation();
this.setState({
previewVisible: true,
});
};
onRemove = () => {
console.log("remvoe")
}
renderFile = url => {
const fileName = url.split("_")[1];
return (<span>
{
isImage(url) ?
<img alt="example" style={{ width: '100%' }} src={url} /> :
(
<div style={{
fontSize: "16px",
color: "#1890ff"
}}>
<p>
<Icon type="file" />
</p>
{fileName}
</div>
)
}
</span>)
}
render() {
const { imageUrl, previewVisible, type } = this.state;
const uploadButton = (
<div>
<Icon type={this.state.loading ? 'loading' : 'plus'} />
<div className="ant-upload-text">Upload</div>
</div>
);
return (<div>
<Upload
accept={type}
name="file"
listType="picture-card"
className="avatar-uploader"
showUploadList={false}
action="api/uploadFile"
onRemove={this.onRemove}
onChange={this.handleChange}
>
{imageUrl ? <div>
{/* <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> */}
{
this.renderFile(imageUrl)
}
{
isImage(imageUrl) ? (<span onClick={this.handlePreview}>
预览 <Icon type="eye" />
</span>) : ""
}
</div> : uploadButton}
</Upload>
<Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
{this.renderFile(imageUrl)}
</Modal>
</div>)
}
}
export default UploadFile;
接收连个参数imageUrl(上传返回值)和type(上传类型)
最后调用