react antv实现图片上传预览
1、引入
import {Upload} from 'antd'
全局引入样式:import 'antd/dist/antd.css'
2、使用
<Upload
name="上传名称,和后台约定"
listType="picture-card"
className="样式类"
showUploadList={false}
action="后台地址"
onChange={上传图片回调,第一个参数为图片信息}
>
图片预览
{imageUrl ? <img src={"http://localhost:3000"+imageUrl} alt="avatar" style={
{ width: '100%' }} /> : uploadButton}
</Upload>
3、设置上传回调
const handleChange = info => {
if (info.file.status === 'uploading') { 上传中
进行图片上传加载动画等操作
return;
}
if (info.file.status === 'done') { 上传成功
在这里进行设置预览图片地址等操作
info.file.response.info为图片在服务器的地址,使用时需要在前面加上服务器地址
}
};
代码示例:
import React,{ useState,useEffect} from 'react'
import { Form,Card,Input,Button, message,Upload,uploadButton} from 'antd'
import { createApi,getOneById,modifyOne} from '../../../utils/auth'
function Edit(props) {
const { getFieldDecorator}=props.form
const [name,setName]=useState('');
const [price,setPrice]=useState(0);
const [imageUrl,setIamgeUrl]=useState('');
const [loading,setLoading]=useState(false);
// var name='';
// var price="";
const uploadButton = (
<div>
{ loading ? 'loading' : "plus"}
<div className="ant-upload-text">Upload</div>
</div>
);
const handleChange = info => {
if (info.file.status === 'uploading') {
setLoading(true);
return;
}
if (info.file.status === 'done') { //上传成功
setLoading(false);
console.log(info);
setIamgeUrl(info.file.response.info);
}
};
useEffect(()=>{
if(props.match.params.id)
{
getOneById(props.match.params.id)
.then(res=>{
console.log(res);
setName(res.name);
setPrice(res.price);
setIamgeUrl(res.coverImg);
})
}
},[])
const submit=(e)=>
{
e.preventDefault();
console.log(e);
props.form.validateFieldsAndScroll((err,value)=>{
if(!err)
{
console.log(value);
//修改
if(props.match.params.id)
{
modifyOne(props.match.params.id,{ ...value,coverImg:imageUrl});
props.history.push('/admin/products');
}else{
//添加数据
createApi({ ...value,coverImg:imageUrl}).then(res=>{
console.log(res);
props.history.push('/admin/products');
})
}
}else{
message.error('请输入正确的内容');
}
})
}
return (
<Card title='商品编辑'>
<Form onSubmit={ e=>submit(e)}>
<Form.Item label='名字'>
{
getFieldDecorator('name',{
initialValue: name,
rules:[{
required:true,
message:'请输入商品名'
}]
})(<Input placeholder='请输入商品名称'></Input>)
}
</Form.Item>
<Form.Item label='价格'>
{
getFieldDecorator('price',{
initialValue: price,
rules:[{
required:true,
message:'请输入商品价格'
}]
})(<Input placeholder='请输入商品价格' ></Input>)
}
</Form.Item>
<Form.Item label='主图'>
<Upload
name="file"
listType="picture-card"
className="avatar-uploader"
showUploadList={ false}
action="http://localhost:3009/api/v1/common/file_upload"
onChange={ (info)=>{ handleChange(info)}}
>
{ imageUrl ? <img src={ "http://localhost:3009"+imageUrl} alt="avatar" style={ { width: '100%' }} /> : uploadButton}
</Upload>
</Form.Item>
<Form.Item><Button htmlType='submit' type='primary'>保存</Button></Form.Item>
</Form>
</Card>
)
}
export default Form.create({ name:'productEdit'})(Edit)
还没有评论,来说两句吧...