cocos2dx-lua http请求下载图片,使用XMLHttpRequest类
HttpFileDownLoadSimple.lua
local downloader = {} --数据拆分,以没1024*5字节拆成一段,打包写入文件 (拆完再拼接,转成字符串) local function getStrData(response) local totalSize = table.getn(response) local onePart = 1024*5 local partData = "" local packTimes = math.floor(totalSize/onePart) print("文件大小: : " , totalSize ) --print(" -- > pack size , times : " , totalSize , packTimes) for i=1,packTimes do local partUnPack = string.char(unpack(response,1+(i-1)*onePart , i*onePart) ) partData = partData..partUnPack --print(" -- > pack new part : " , 1+(i-1)*onePart , i*onePart) end --print(" -- > pack end part : " , packTimes*onePart+1 , totalSize) local endUnpack = string.char(unpack(response , packTimes*onePart+1 , totalSize) ) partData = partData..endUnpack return partData end --下载图片 function downloader:DownLoadImage(url,saveName,callBack) local xhr = cc.XMLHttpRequest:new() xhr.responseType = cc.XMLHTTPREQUEST_RESPONSE_ARRAY_BUFFER xhr:open("GET", url) --self.callBack = callBack local function onReadyStateChanged() print("---------net--------- xhr.readyState xhr.status",xhr.readyState,xhr.status) if xhr.readyState == 4 and (xhr.status >= 200 and xhr.status < 207) then print(" ---> 下载图片返回数据 : " , xhr.statusText ) local response = xhr.response local strInfo = getStrData(response) io.writefile("user/"..saveName, strInfo, "w+b") --self:callback("down load ok" , saveName) --self. callBack(saveName) else print(" --- > error xhr.readyState is:", xhr.readyState, "xhr.status is: ",xhr.status) self:callbackErr(xhr.readyState, xhr.status) end if xhr.status == 200 then print("xhr.readyState xhr.status",xhr.readyState,xhr.status) --req.callback(code,fullFileName,req) end xhr:unregisterScriptHandler() end xhr:registerScriptHandler(onReadyStateChanged) xhr:send() end cc.exports.HttpFileDownLoadSimple = downloader return downloader
调用代码:
local list = {} list[1] = {id = 666,url = "http://life.southmoney.com/tuwen/UploadFiles_6871/201809/20180925104703150.jpg"} list[2] = {id = 777,url = "http://img.52z.com/upload/news/image/20180914/20180914034357_53554.jpg"} function downCallBack(name) print(name) end local u1 = list[1] local u2 = list[2] HttpFileDownLoadSimple:DownLoadImage(u1.url,"head"..u1.id..".jpg",downCallBack)
文件下载路径:(在代码里可以改)
运行目录或项目根目录 user 文件夹