cocoscreator 下载图片保存本地

时间:2025-03-31 11:58:36
test:function (url, callback) { console.log('remote test'); var dirpath = jsb.fileUtils.getWritablePath() + 'img/'; var filepath = dirpath + 'picture' + '.png'; console.log('remote filepath: ' + filepath); function loadEnd(){ .load(filepath, function(err, tex){ if( err ){ cc.error(err); }else{ var spriteFrame = new (tex); if( spriteFrame ){ spriteFrame.retain(); callback(spriteFrame); } } }); } if( jsb.fileUtils.isFileExist(filepath) ){ console.log('Remote is find' + filepath); loadEnd(); return; } var saveFile = function(data){ if( typeof data !== 'undefined' ){ if( !jsb.fileUtils.isDirectoryExist(dirpath) ){ jsb.fileUtils.createDirectory(dirpath); } if( jsb.fileUtils.writeDataToFile( new Uint8Array(data) , filepath) ){ console.log('Remote write file succeed.'); loadEnd(); }else{ console.log('Remote write file failed.'); } }else{ console.log('Remote download file failed.'); } }; var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { console.log("Remote " +xhr.readyState); console.log("Remote " +xhr.status); if (xhr.readyState === 4 ) { if(xhr.status === 200){ xhr.responseType = 'arraybuffer'; saveFile(xhr.response); }else{ saveFile(null); } } }.bind(this); xhr.open("GET", url, true); xhr.send(); }