Air客户端与服务器文件同步基本框架FileSync

/**
* AUTHOR: 李同刚 于 二零一一年四月
* 文件同步操作封装,自动处理上传和下载数据发生的异常:
* - 网络原因 或 服务器停止造成数据不完整
* - 把服务端返回的错误信息当数据下载
* 调用示例:
* FileSync.download('http://localhost/big.zip','mydocument/foo.zip',
* function(event, msg){ //下载失败的回调函数 event参数表示事件对象 msg参数表示错误信息
* alert(msg+ " | " + event.target)
* return true // 返回true保留不合法数据 false 删除数据
* },
* function(file){ //下载成功的回调函数 file参数为下载的文件对象File
* alert("success: " + file.nativePath)
* }
* )
*/


var FileSync = {}

/**
* 自定义事件类型
*/
FileSync.__events__ = {

BadDataErrorEvent : function(target, text){
this.text = text ? text : '下载的数据不完整'
this.target = target
},

IOError : function(target, text){
this.text = text ? text : '文件被占用,无法操作'
this.target = target
}
}
FileSync.BadDataErrorEvent = FileSync.__events__.BadDataErrorEvent
FileSync.BadDataErrorEvent.prototype = new air.ErrorEvent('BadData',false,false,null,10000)
FileSync.IOError = FileSync.__events__.IOError

/**
* 下载数据
* @param {Object} url
* @param {Object} localFilePath
* @param {Object} exceptionCallback
* @param {Object} successCallback
*/
FileSync.__download__ = {

main : function(url,localFilePath,exceptionCallback,successCallback){
var file = air.File.documentsDirectory
var filePath = localFilePath.substring(0, localFilePath.lastIndexOf("/")+1)
var fileName = localFilePath.substring(localFilePath.lastIndexOf("/")+1)
var path = file.resolvePath(filePath);
if(!path.exists)
path.createDirectory();
FileSync.__download__.baseDown(url, filePath, fileName ,exceptionCallback,successCallback)
},

baseDown : function(url, filePath, fileName ,exceptionCallback,successCallback){
var stream = new air.URLStream();
FileSync.__download__.addListener(stream,filePath, fileName,exceptionCallback,successCallback)
var request = new air.URLRequest(url)
try{
stream.load(request)
} catch (error) {
if(stream.connected)
stream.close()
air.trace("Unable to load requested document.")
}
},

addListener : function(stream, filePath , fileName ,exceptionCallback,successCallback){

var currentPosition = 0, downloadCompleteFlag = false, isExceptionComplete = false, bytesTotal
var temFileName = fileName + '.tem'
var file = air.File.documentsDirectory.resolvePath(filePath + temFileName)
var fileStream = new air.FileStream()
fileStream.open(file, air.FileMode.WRITE)

var processExceptionComplete = function (event, errorText) {
try {
isExceptionComplete = true
downloadCompleteFlag = true
fileStream.close()
if (stream.connected)
stream.close()
// 处理异常下载的数据
var temFile = air.File.documentsDirectory.resolvePath(filePath + temFileName)
if (exceptionCallback && typeof(exceptionCallback) == 'function') {
var retn = exceptionCallback(event, errorText ? errorText : event.text)
if (!retn && temFile.exists)
temFile.deleteFile()
}
}catch(error){
air.trace("processExceptionComplete ERROR: " + error)
}
air.trace("processExceptionComplete: " + event)
}

var openHandler = function(event) {
air.trace("openHandler: " + event)
}

var httpStatusHandler = function (event) {
air.trace("httpStatusHandler: " + event)
var ok = 200
if(event.status != 200 && (!isExceptionComplete))
processExceptionComplete(event, 'HTTP状态异常[HttpStatus: ' + event.status + ']')
}

var progressHandler = function (event) {
air.trace("progressHandler: " + event)
bytesTotal = event.bytesTotal
var bytes = new air.ByteArray()
var thisStart = currentPosition
currentPosition += stream.bytesAvailable
try{
stream.readBytes(bytes, thisStart)
fileStream.writeBytes(bytes, thisStart)
}catch(e){
if(!isExceptionComplete)
processExceptionComplete(event, 'ProgressEvent事件异常,内存溢出')
air.trace("progressHandler exception: " + e)
}

}

var ioErrorHandler = function (event) {
if(!isExceptionComplete)
processExceptionComplete(event, 'IOErrorEvent事件异常')
air.trace("ioErrorHandler: " + event)
}

stream.addEventListener(air.ProgressEvent.PROGRESS, progressHandler);
stream.addEventListener(air.Event.OPEN, openHandler)
stream.addEventListener(air.HTTPStatusEvent.HTTP_STATUS, httpStatusHandler)
stream.addEventListener(air.IOErrorEvent.IO_ERROR, ioErrorHandler);
stream.addEventListener(air.Event.COMPLETE, function(event){
air.trace("completeHandler: " + event)
if (!isExceptionComplete) {
// 校验数据
var temFile = air.File.documentsDirectory.resolvePath(filePath + temFileName)
if (!temFile) {
processExceptionComplete(new FileSync.BadDataErrorEvent(temFile.nativePath, '文件不存在'))
return
}
if (temFile.size != bytesTotal) {
processExceptionComplete(new FileSync.BadDataErrorEvent(temFile, '文件字节数小于服务器数据['+temFile.size+'<'+bytesTotal+']'))
return
}
// 数据合法
fileStream.close()
if (stream.connected)
stream.close()
var file = air.File.documentsDirectory.resolvePath(filePath + fileName)
try{
temFile.copyTo(file, true);
}catch (error){
if(error.constructor == window.runtime.flash.errors.IOError){
processExceptionComplete(new FileSync.IOError(temFile, '目标文件被占用['+filePath + fileName+']'))
return
}
}
if(successCallback && typeof(successCallback) == 'function')
successCallback(file)
}
})
}
}
/** 公开调用函数 **/
FileSync.download = FileSync.__download__.main

FileSync.upload = function(){

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值