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)