react上傳

1.創(chuàng)建一個上傳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') {
//返回服務(wù)器路徑和文件名
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;
接收連個參數(shù)imageUrl(上傳返回值)和type(上傳類型)


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

最后調(diào)用


image.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • var form = new FormData() var fileObj = document.getE...
    CL_5500閱讀 6,586評論 0 0
  • mean to add the formatted="false" attribute?.[ 46% 47325/...
    ProZoom閱讀 3,219評論 0 3
  • 以下內(nèi)容是我在學習和研究React時,對React的特性、重點和注意事項的提取、精練和總結(jié),可以做為React特性...
    科研者閱讀 8,416評論 2 21
  • 前言: 本文分為2個部分: 1.前半部分為5個前置知識點,簡要介紹了React中的props和state、dva中...
    Sunflow007閱讀 1,594評論 0 0
  • 一、每日必做模塊 學習--英語、閱讀、課本知識、考試題目 運動--因為今天不洗頭,所以今天沒跑,平時的跑步周期是2...
    小小小grow閱讀 270評論 0 0

友情鏈接更多精彩內(nèi)容