Total Pageviews

Friday, March 29, 2013

Writing large files on mobile\android\ios from web using Flex AIR

Generally, we tend to load a file, read it and then write it on the disk, which works absolutely fine on web\desktop. But in case of mobiles\tablets, memory is a huge constraint. Smaller files may still work as intended, but in case of larger files(> 300MB), FileStream.readBytes or FileStream.writeBytes would fail as app would try to load the data in memory which would be very less comparatively and app would crash in that case. Hence, we could instead read and write data in chunks which would not affect the memory as much.

getRemoteFile("http://www.someserver.com/mobilefiles/someLargeDBFile.sqlite");

private var urlStream:URLStream;  
public function getRemoteFile(path:String):void 

            urlStream = new URLStream();
            var urlReq:URLRequest = new URLRequest(path); 
            urlStream.addEventListener(Event.COMPLETE, loaded);
            urlStream.addEventListener(ProgressEvent.PROGRESS, onProgress);
            urlStream.load (urlReq); 
 }

private function onProgress(event:ProgressEvent):void
{
           writeDataToDisk();
}

private function writeDataToDisk():void
        {
            fileLocal = File.applicationStorageDirectory.resolvePath(folderName+"\\"+fileName);
            var bytes:ByteArray = new ByteArray();
            if ( urlStream.bytesAvailable == 0 ) return;
            if ( urlStream.connected )
            {
                urlStream.readBytes(bytes, bytes.length);
                fs = new FileStream();
                fs.addEventListener(Event.CLOSE, onClose);
                fs.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
                fs.open( fileLocal, FileMode.APPEND );
                fs.writeBytes( bytes );
                bytesOffset = bytes.length;
                fs.close();
            } 
        }

No comments:

Post a Comment