1、单文件上传(选择图片后直接上传)
<ImagePicker
files={files}
length={1}
disableDelete={true}
onChange={this.onChange}
selectable={files.length==0}
multiple={false}
/>
onChange = (files, type, index) => {
const { dispatch } = this.props;
if (type == 'add') {
var file = files[files.length - 1].file
let formData = new FormData();
formData.append("file", file);
//files[files.length - 1].url = '../../../../src/white.png'
this.setState({files,animating:true},()=>{
dispatch({
type:'user/fetchChangeAvatar',
payload:formData,
callback:(res)=>{
this.setState({
avatar:res.data.url,
animating:false
})
}
})
})
} else {
this.setState({files});
}
}
2、多文件上传(正常选择图片,点击提交时上传图片,后台返回图片路径的字符串并以逗号间隔,再进行其他保存操作)
<ImagePicker
files={files}
onChange={this.onImgChange}
length={3}
selectable={files.length < 3}
multiple={true}
/>
onImgChange = (files, type, index) => {
if(type=='add'){
if(files.length>3){
Toast.fail('上传图片不能大于3张',1);
return ;
}
this.setState({ files})
}else{
this.setState({ files })
}
addComment = () => {
const { dispatch, match, form } = this.props;
//console.log(this.props)
const alert = Modal.alert;
form.validateFields((error, fieldsValue) => {
if (error) {
Toast.fail('评论内容不能为空!!', 1)
return;
}
alert('发布评论', '您确定退出发布吗?', [
{ text: '取消', onPress: () => console.log('cancel') },
{
text: '确定', onPress: () => {
if(this.state.files.length>0){
let formData = new FormData();
for (let i = 0; i < this.state.files.length; i++) {
// antd mobile 把 File 对象放在了 .file中
let file = this.state.files[i].file;
formData.append('file', file);
}
this.setState({animating:true})
dispatch({
type: 'activity/addCommentImgs',
payload: formData,
callback: (res) => {
this.setState({
str: res.data.url,
animating:false
},()=>{
dispatch({
type: "activity/addComment",
payload: {
pgid: match.params.id,
personnelid: localStorage.getItem('userid'),
thoughts: fieldsValue.des,
imgs: this.state.str,
thestar: this.state.stars
},
callback: res => {
if (res.success) {
Toast.success('评论成功!', 1);
router.goBack()
}
}
})
});
}
})
}else{
dispatch({
type: "activity/addComment",
payload: {
pgid: match.params.id,
personnelid: localStorage.getItem('userid'),
thoughts: fieldsValue.des,
imgs: '',
thestar: this.state.stars
},
callback: res => {
this.setState({
animating:false
})
if (res.success) {
Toast.success('评论成功!', 1);
router.goBack()
}
}
})
}
}
},
])
});
}