1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
| import React from 'react'; import PropTypes from 'prop-types'; import { Upload, Button, Icon, Modal } from 'antd';
import { getUploadTokenAndProgress, uploadFileThunk, finishFileUpload } from '../../../unit/fetch';
const propTypes = { multiple: PropTypes.bool, chunkSize: PropTypes.number, threadNum: PropTypes.number, accept: PropTypes.string, onChange: PropTypes.func }
const Dragger = Upload.Dragger;
const FILE_STATE = { PREPARING: Symbol(), WAITING: Symbol(), UPLOADING: Symbol(), FINISHED: Symbol(), ERRORED: Symbol() };
class LargeFileUpload extends React.Component { constructor({ multiple = false, chunkSize = 5 * 1024 * 1024, threadNum = 1, accept = '' }) { super(); this.state = { multiple, chunkSize, threadNum, accept, disabled: false, fileList: [], isPrepared: false };
this.submit = this.submit.bind(this); this.sliceFile = this.sliceFile.bind(this); this.md5File = this.md5File.bind(this); this.toUpload = this.toUpload.bind(this); this.onCompleted = this.onCompleted.bind(this);
import('../../../unit/tool/MD5File').then(MD5WorkerUrl => { this.MD5Worker = new Worker(MD5WorkerUrl); this.MD5Worker.onmessage = ({data}) => { const fileInfo = this.state.fileList.find( info => info.id === data.id ); if(!fileInfo) { return ; } fileInfo.MD5 = data.hash; fileInfo.state = FILE_STATE['WAITING']; let isPrepared = false; for (let info of this.state.fileList) { if (info.state === FILE_STATE['PREPARING']) { isPrepared = true; break; } } this.setState({ isPrepared }); }; })
}
onCompleted() { if (typeof this.props.onChange === 'function') { this.props.onChange({ success: this.state.fileList.filter(info => info.state === FILE_STATE['FINISHED']).map(info => {return {token: info.token, name: info.config.file.name}}), total: this.state.fileList.length, isCompleted: !this.state.fileList.some(info => ![FILE_STATE['FINISHED'], FILE_STATE['ERRORED']].includes(info.state)) }); } }
sliceFile(file, chunkCount) { let sliceRst = []; let blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice; for (let i = 0, start, end; i < chunkCount; i++) { start = i * this.state.chunkSize; end = Math.min(file.size, start + this.state.chunkSize); sliceRst.push(blobSlice.call(file, start, end)); } return sliceRst; }
md5File(fileInfo) { this.MD5Worker.postMessage({ 'fileChunk': this.sliceFile(fileInfo.config.file, fileInfo.chunkCount), 'id': fileInfo.id }); }
toUpload(fileInfo) { return new Promise(async (resolve, reject) => { const successThunkArr = new Set(); const fileChunkArray = this.sliceFile(fileInfo.config.file, fileInfo.chunkCount); const completeUploadingFile = async () => { fileInfo.config.onProgress({percent: 100}); try{ const { token } = await finishFileUpload({ uploadToken: fileInfo.uploadToken, patchSum: fileInfo.chunkCount }); fileInfo.token = token; fileInfo.state = FILE_STATE['FINISHED']; fileInfo.config.onSuccess(); resolve(); } catch(e) { failureUploadThunk(); } }; const failureUploadThunk = () => { fileInfo.state = FILE_STATE['ERRORED']; fileInfo.config.onError(); resolve(); }; const successUploadThunk = curChunkIndex => { successThunkArr.add(+curChunkIndex); if (successThunkArr.size === fileInfo.chunkCount) { completeUploadingFile(); } else if (successThunkArr.size < fileInfo.chunkCount) { fileInfo.config.onProgress({percent: (successThunkArr.size / fileInfo.chunkCount).toFixed(2) * 100 }); curChunkIndex && uploadThunk(successThunkArr.size); } }; const uploadThunk = (currentSuccessThunkNum, chunkIndex) => { return new Promise(async resolve => { const curChunkIndex = chunkIndex + 1 ? chunkIndex : currentSuccessThunkNum + Math.min(this.state.threadNum, fileInfo.chunkCount) - 1; let failureTimes = 0; function toUploadThunk() { return new Promise(async resolve => { try { await uploadFileThunk({ uploadToken: fileInfo.uploadToken, order: curChunkIndex, file: fileChunkArray[curChunkIndex] }); successUploadThunk(curChunkIndex); resolve(); } catch(e) { failureTimes++; if (failureTimes < 3) { toUploadThunk(); } else { failureUploadThunk(); } } }) }
if(curChunkIndex >= fileInfo.chunkCount) { return }
try { const fileSize = fileInfo.config.file.size; const { uploadToken, thunkArr } = await getUploadTokenAndProgress({ md5: fileInfo.MD5, fileSize, fileName: encodeURIComponent(fileInfo.config.file.name) }); fileInfo.uploadToken = uploadToken; thunkArr.forEach( index => successThunkArr.add(+index) );
if (successThunkArr.has(+curChunkIndex)) { successUploadThunk(curChunkIndex); } else { await toUploadThunk(); } resolve() } catch(e) { failureUploadThunk(); } }) };
await uploadThunk(0, 0);
for(let i = 1, len = Math.min(this.state.threadNum + 1, fileInfo.chunkCount); i < len; i++) { uploadThunk(successThunkArr.size, i); } }); }
async submit() { if(!this.state.fileList.length) { Modal.info({ title: '提示', content: ( <div> <p>请选择文件后,再提交!</p> </div> ) }); return; } for(let fileInfo of this.state.fileList) { if (fileInfo.state === FILE_STATE['WAITING']) { fileInfo.state = FILE_STATE['UPLOADING']; await this.toUpload(fileInfo); } } this.onCompleted(); }
render() { const draggerProps = { multiple: this.state.multiple, accept: this.state.accept, disabled: this.state.disabled, customRequest: config => { let fileInfo = { id : config.file.uid, state: FILE_STATE['PREPARING'], chunkCount: Math.ceil(config.file.size / this.state.chunkSize), MD5: null, uploadToken: null, token: null, config }; console.log(config); this.setState({ fileList: [...this.state.fileList, fileInfo], disabled: !this.state.multiple, isPrepared: true }, this.onCompleted); this.md5File(fileInfo); }, onRemove: file => { const fileList = [...this.state.fileList.filter(info => info.id !== file.uid)]; let isCompleted = !fileList.some(info => ![FILE_STATE['FINISHED'], FILE_STATE['ERRORED']].includes(info.state)); this.setState({ fileList, disabled: fileList.length && !this.state.multiple }, () => { isCompleted && this.onCompleted(); }); } };
return (<div> <Dragger {...draggerProps}> {this.props.children ? this.props.children : <div> <p className="ant-upload-drag-icon"><Icon type="inbox" /></p> <p className="ant-upload-text">点击选择文件或将文件拖拽到这里</p> </div>} </Dragger> <div style={{marginTop: '10px'}}> <Button ghost type="primary" size="small" onClick={this.submit} loading={this.state.isPrepared}>上传</Button> { this.state.isPrepared && <span style={{marginLeft: '7px'}}>正在读取文件,请稍后!</span>} </div> </div>); } }
LargeFileUpload.propTypes = propTypes;
export default LargeFileUpload;
|