import IUploadPattern from "./IUploadPattern" ; import Uploader from "../Uploader" ; import DirectTask from "../task/DirectTask" ; import log from "../../util/Log" ; /**
 * 直接上传
 */ class DirectUploadPattern implements IUploadPattern { private uploader : Uploader ; private task : DirectTask ; constructor ( uploader ) { this . uploader = uploader ; } param task upload ( task ) { this . task = task ; this . uploader . getToken ( task ) . then ( ( token ) => { task . startDate = new Date ( ) ; this . uploadFile ( token ) ; } ) ; } param token returns { FormData } private createFormData ( token ) { let task = this . task ; let formData = new FormData ( ) ; if ( task . key !== null && task . key !== undefined ) { formData . append ( 'key' , task . key ) ; } formData . append ( 'token' , token ) ; formData . append ( 'file' , task . file ) ; log . d ( `创建formData对象` ) ; return formData ; } param token private uploadFile ( token ) { let task = this . task ; let xhr = new XMLHttpRequest ( ) ; xhr . upload . onprogress = ( e ) => { if ( e . lengthComputable ) { let progress = Math . round ( ( e . loaded * 100 ) / e . total ) ; if ( task . progress < progress ) { task . progress = progress ; this . uploader . listener . onTaskProgress ( task ) ; } } } ; xhr . upload . onload = ( ) => { if ( task . progress < 100 ) { task . progress = 100 ; this . uploader . listener . onTaskProgress ( task ) ; } } ; let url = this . uploader . domain ; url += ( ( /\?/ ) . test ( this . uploader . domain ) ? "&" : "?" ) + ( new Date ( ) ) . getTime ( ) ; xhr . open ( 'POST' , url , true ) ; xhr . onreadystatechange = ( ) => { if ( xhr . readyState == XMLHttpRequest . DONE ) { if ( xhr . status == 200 && xhr . responseText != '' ) { task . result = JSON . parse ( xhr . responseText ) ; task . isSuccess = true ; task . isFinish = true ; task . endDate = new Date ( ) ; this . uploader . listener . onTaskSuccess ( task ) ; } else if ( this . retryTask ( task ) ) { log . w ( `${ task . file . name }上传失败,准备开始重传` ) ; this . uploader . listener . onTaskRetry ( task ) ; } else { log . w ( `${ task . file . name }上传失败` ) ; task . error = xhr . response ; task . isSuccess = false ; task . isFinish = true ; task . endDate = new Date ( ) ; this . uploader . listener . onTaskFail ( task ) ; } if ( this . uploader . isTaskQueueFinish ( ) ) { log . d ( '上传队列结束' ) ; this . uploader . tasking = false ; this . uploader . listener . onFinish ( this . uploader . taskQueue ) ; } } } ; let formData = this . createFormData ( token ) ; xhr . send ( formData ) ; log . d ( '发送ajax post 请求' ) ; } param task returns { boolean } private retryTask ( task ) { log . d ( "开始尝试重传" ) ; if ( task . retry >= this . uploader . retry ) { log . w ( `${ task . file . name }达到重传次数上限${ this . uploader . retry },停止重传` ) ; return false ; } task . retry ++ ; log . w ( `${ task . file . name }开始重传,当前重传次数${ task . retry }` ) ; this . upload ( task ) ; return true ; } } export default DirectUploadPattern ;