注意:imagePicker只是圖片選擇器者甲,一般用于上傳圖片前的文件選擇操作岸蜗,但不包括圖片上傳的功能. 因?yàn)榉庋b了一個(gè)帶上傳的
上傳的核心是封裝好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
// 如果是添加蝎毡,則獲取最后一個(gè)上傳
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