import React, {Component} from 'react'
|
import PropTypes from 'prop-types'
|
import { Upload, message, Button, Icon, Progress } from 'antd'
|
import Api from '@/api'
|
import './index.scss'
|
|
let service = window.GLOB.service ? (/\/$/.test(window.GLOB.service) ? window.GLOB.service : window.GLOB.service + '/') : ''
|
let Url = '/Upload'
|
if (process.env.NODE_ENV === 'production') {
|
Url = document.location.origin + '/' + service + 'zh-CN/Home/Upload'
|
}
|
|
class FileUpload extends Component {
|
static propTpyes = {
|
value: PropTypes.array // 按钮信息、表单列表
|
}
|
|
state = {
|
baseUrl: Url,
|
percent: 0,
|
showprogress: false
|
}
|
|
init = async () => {
|
try {
|
const OSSData = await this.mockGetOSSData()
|
|
this.setState({
|
OSSData
|
})
|
} catch (error) {
|
message.error(error)
|
}
|
}
|
|
onChange = ({ fileList }) => {
|
const { onChange } = this.props
|
|
if (onChange) {
|
onChange([...fileList])
|
}
|
}
|
|
onRemove = file => {
|
const { value, onChange } = this.props
|
|
const files = value.filter(v => v.url !== file.url)
|
|
if (onChange) {
|
onChange(files)
|
}
|
}
|
|
getExtraData = () => {
|
return {
|
RootPath: 'Content/images/upload/'
|
}
|
}
|
|
shardupload = (file, shardSize, shardCount, i, fileList) => {
|
let start = i * shardSize
|
let end = Math.min(file.size, start + shardSize)
|
let form = new FormData()
|
|
form.append('file', file.slice(start, end)) //slice方法用于切出文件的一部分
|
form.append('RootPath', 'Content/images/upload/')
|
form.append('name', file.name)
|
form.append('total', shardCount)
|
form.append('index', i + 1)
|
|
if (i < shardCount) {
|
i++
|
Api.getFileUpload(form).then(res => {
|
if (res) {
|
this.setState({
|
percent: Math.floor(100 * (i / shardCount))
|
})
|
this.shardupload(file, shardSize, shardCount, i, fileList)
|
}
|
})
|
} else {
|
this.setState({
|
percent: 100
|
}, () => {
|
setTimeout(() => {
|
this.setState({
|
showprogress: false,
|
percent: 0
|
})
|
}, 200)
|
})
|
}
|
}
|
|
beforeUpload = (file, fileList) => {
|
let shardSize = 2 * 1024 * 1024
|
// let shardSize = 3 * 1024
|
|
if (file.size > shardSize) {
|
this.setState({
|
showprogress: true,
|
percent: 0
|
})
|
let shardCount = Math.ceil(file.size / shardSize)
|
this.shardupload(file, shardSize, shardCount, 0, fileList)
|
return false
|
} else {
|
return true
|
}
|
}
|
|
render() {
|
const { value } = this.props
|
const { showprogress, percent, baseUrl } = this.state
|
|
const props = {
|
name: 'file',
|
disabled: showprogress,
|
fileList: value,
|
action: baseUrl,
|
method: 'post',
|
multiple: true,
|
// headers: {'RootPath': 'Content/images/upload/'},
|
onChange: this.onChange,
|
onRemove: this.onRemove,
|
data: this.getExtraData,
|
beforeUpload: this.beforeUpload,
|
}
|
return (
|
<Upload {...props}>
|
<Button>
|
<Icon type="upload" /> 点击上传
|
</Button>
|
{showprogress ? <Progress percent={percent} size="small" /> : null}
|
</Upload>
|
)
|
}
|
}
|
|
export default FileUpload
|