How to write an image in the application directory using AIR?

advertisements

I'm trying to save an image to the application directory by opening a file stream and write the bytes from a bitmap data. I added some events listeners for testing the file stream process but I don't receive any response event. Can you take a look over my code and tell me where might be the problem.

        var bd:BitmapData = new BitmapData(CANVAS_WIDTH, CANVAS_HEIGHT);
        bd.draw(currentDrawing);
        var jpgEncoder:JPGEncoder = new JPGEncoder(100);
        var ba:ByteArray = jpgEncoder.encode(bd);

        var newImage:File = File.applicationDirectory.resolvePath("images/test.jpg");
        var fileStream:FileStream = new FileStream();
        fileStream.open(newImage, FileMode.UPDATE);
        fileStream.writeBytes(ba);
        fileStream.addEventListener(Event.CLOSE, fileClosed);
        fileStream.addEventListener(Event.COMPLETE, fileComplete);
        fileStream.addEventListener(IOErrorEvent.IO_ERROR, fileError);
        fileStream.close();

        function fileClosed(event:Event):void {
            outputText.text = "close";
        }

        function fileComplete(event:Event):void {
            outputText.text = "complete";
        }
        function fileError(event:IOErrorEvent):void {
            outputText.text = "error";
        }


AIR security forbids writing into app directory.
If you absolutely need to write some file into app dir, you can use native helper to do that (cmd.exe on Windows, for example.) But consider using File.applicationStorageDirectory instead - it is writable, but hidden somewhere in user profile.