-- 文件下载器 local FileDownloader = class("FileDownloader") -- urls : 下载地址 -- fileName :保存在本地的文件名 -- onFinishCallback : 完成后的回调 function FileDownloader:ctor(urls, atts, onFinishCallback) self.urls = urls self.atts = atts self.onFinishCallback = onFinishCallback; end -- 开启下载 function FileDownloader:start() local priority = 0 local startPos = self.atts.offset or 0 local dataSize = self.atts.compressedSize or 0 local timebegin; local index = 0; local function downloadFileFromUrl() local function onUpdateFirst(status , data) if status == "successed" then -- 打印下载文件的耗时 local timeEnd = os.time() logI(string.format("FileDownloader() cost time = %4s , size = %8s , file = %s", timeEnd - timebegin, dataSize, self.atts.name)) -- 下载成功后将数据保存为本地文件 self:onDownloadSuccessed(data); else -- 下载失败后再次请求下载 downloadFileFromUrl() end end index = index + 1 if not self.urls[index] then logE("FileDownloader:start() url is nil") return end timebegin = os.time() self.task = cc.CURLManager:getInstance():createTask(self.urls[index], onUpdateFirst , priority , startPos , dataSize); end downloadFileFromUrl(); end -- 取消下载 function FileDownloader:cancel() if self.task then cc.CURLManager:getInstance():cancelTask(self.task); self.task = nil end end function FileDownloader:onDownloadSuccessed(data) local targetFilename = cc.FileUtils:getInstance():getWritablePath() .. self.atts.md5 local uncompressData = lzma.uncompress(data); -- 解压成功 if uncompressData then local targetFile = io.open(targetFilename , "wb"); if targetFile == nil then return; end targetFile:write(uncompressData); targetFile:close(); else logE("文件解压失败:" , self.atts.name , "压缩文件大小:" , #data , "/" , self.atts.compressedSize) ; return; end -- win32平台下面文件系统是不会起作用的 if not isWin32Platform() then -- 加到文件系统中 self:addFile(); --[[ -- 检查MD5 local md5Result = cc.FilePackage:calcFileMd5(targetFilename); if md5Result ~= self.atts.md5 then logE("文件下载完毕,但是文件的md5跟服务器上面记录的md5不一致,删除本地文件:", targetFilename) os.remove(targetFilename); return; end --]] end self:onFinish() end -- 添加文件信息到打包文件系统中 function FileDownloader:addFile() local info = { isRomFile = false; origin = self.atts.origin; name = self.atts.name; md5 = self.atts.md5; size = tonumber(self.atts.size), realFilePath = getWritableFullName(self.atts.md5); }; print("加到文件系统" , info.realFilePath , self.atts.md5 , self.atts.name); cc.FilePackage:getInstance():addFile(info); end -- 下载完成 function FileDownloader:onFinish() if self.onFinishCallback then self.onFinishCallback() end end return FileDownloader