react上传

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 (
{
isImage(url) ?
example :
(

fontSize: "16px",
color: "#1890ff"
}}>




{fileName}

)
}
)

}

render() {
const { imageUrl, previewVisible, type } = this.state;
const uploadButton = (



Upload


);
return (

accept={type}
name="file"
listType="picture-card"
className="avatar-uploader"
showUploadList={false}
action="api/uploadFile"
onRemove={this.onRemove}
onChange={this.handleChange}
>
{imageUrl ?

{/* avatar */}
{
this.renderFile(imageUrl)
}
{
isImage(imageUrl) ? (
预览
) : ""
}
: uploadButton}


{this.renderFile(imageUrl)}

)
}
}

export default UploadFile;
接收连个参数imageUrl(上传返回值)和type(上传类型)


微信截图_20200324142643.png
微信截图_20200324142659.png
微信截图_20200324142719.png

最后调用


image.png

你可能感兴趣的:(react上传)