React后台管理手动封装图片上传组件
分为两个文件夹,index.js(逻辑文件) styled.js(样式文件)
index.js文件,编写完成之后在对应的地方引入即可
import React from "react"
import { UploadContainer } from "./styled"
import { Icon ,message} from "antd"
import { fetch as fetchPro } from "whatwg-fetch"
class Upload extends React.Component {
constructor(props) {
super(props)
this.state = {
imgUrl: ""
}
if (this.props.value) {
this.state.imgUrl = this.props.value
}
}
render() {
let { imgUrl } = this.state
return (
<UploadContainer>
<input type="file" onChange={this.handleUpdate.bind(this)} ref="files" />
<div className="imgContent">
{imgUrl ? <img src={imgUrl} /> : <Icon type="plus" style={{ fontSize: 26 }} />}
</div>
</UploadContainer>
)
}
async handleUpdate() {
let fileImg = this.refs.files.files[0];
let formData = new FormData()
formData.append("filesImg", fileImg)//第一个参数为后端规定字段,第二个参数时需要上传的图片
let data = await fetchPro("/ajax/upload/files", {
method: "post",
body: formData
}).then(res => res.json())//第一个参数为地址,第二个参数为配置项
if(data.data.urlPath){
this.setState({
imgUrl:data.data.urlPath
})
}else{
message.error(data.data.info)
}
}
}
export default Upload
styled.js文件
import styled from "styled-components" export const UploadContainer = styled.div` width:110px; height:110px; border:1px dashed #ccc; position:relative; input{ opacity:0; width:110px; height:100%; position:absolute; left:0; top:0; z-index:2; } .imgContent{ padding:5px; width:100%; height:100%; position:absolute; left:0; top:0; display:flex; justify-content:center; align-items:center; img{ width:100%; height:100%; } } `