image.png注意:imagePicker只是图片选择器,一般用于上传图片前的文件选择操作,但不包括图片上传的功能. 因为封装了一个带上传的
上传的核心是封装好FormData
import React from 'react'
import { ImagePicker, Toast } from 'antd-mobile'
/**
<AppImagePicker
initFiles={[{
url: 'https://zos.alipayobjects.com/rmsportal/PZUUCKTRIHWiZSY.jpeg',
id: '2121',
}]}
type='edit'
maxLength={2}
receiveNewFiles={(files)=>{console.log('new files', files)}}
/>
*/
interface ImagePickerState {
files: any //[url,file, id]
}
interface ImagePickerProps {
diyprops?: any
type: 'display' | 'edit'
initFiles?: any
maxLength?: number
receiveNewFiles?(files: any): void
}
class AppImagePicker extends React.Component<
ImagePickerProps,
ImagePickerState
> {
constructor(props: ImagePickerProps) {
super(props)
this.state = {
files: props.initFiles || []
}
}
static getDerivedStateFromProps(props: ImagePickerProps, state: ImagePickerState) {
if (!state.files || state.files.length == 0) {
if (props.initFiles) {
return {
files: props.initFiles
}
}
}
}
onChange = (files: any, type: any, index: any) => {
const {
receiveNewFiles
} = this.props
// 如果是添加,则获取最后一个上传
if (type === 'add') {
let currentFile = files[files.length - 1].file
let formData = new FormData();
formData.append("file", currentFile);
fetch("xxxxxxxxx", {
method: 'POST',
headers: {
},
body: formData,
}).then((response) => response.json())
.then((responseData) => {
if (responseData.content && responseData.content.downloadUrl) {
currentFile.url = responseData.content.downloadUrl
this.setState({
files: files
}, () => {
receiveNewFiles && receiveNewFiles(files)
});
} else {
files.splice(-1, 1)
Toast.fail('图片上传失败!')
}
}).catch((err) => {
console.log(err)
files.remove(-1, 1)
Toast.fail('图片上传异常!')
});
} else {
this.setState({
files: files
}, () => {
receiveNewFiles && receiveNewFiles(files)
});
}
}
render() {
const {
diyprops,
type,
maxLength
} = this.props
const {
files
} = this.state
return (
<ImagePicker
{...diyprops}
files={files}
selectable={type == 'edit' && (!maxLength || files.length < maxLength)}
disableDelete={type != 'edit'}
onChange={this.onChange}
/>
)
}
}
export default AppImagePicker
网友评论