Search code examples
actionscript-3apache-flexair

Adobe AIR - Save image on hard drive


I found the below snippet to save an image to a specific folder with Adobe AIR.

How to modify it that the "Save As" OS-window comes up first? (So users can choose where to save the image on the hard-drive)

var arrBytes:ByteArray = PNGEncoder.encode(bmd);
    var file:File = File.desktopDirectory.resolvePath(folderName + "/" + fileName + fileNum + ".png");
    var fileStream:FileStream = new FileStream();
    //
    fileStream.open(file, FileMode.WRITE);
    fileStream.writeBytes(arrBytes);
    fileStream.close();

Thanks.


Solution

  • Use File.browseForSave:

    import flash.filesystem.*;
    import flash.events.Event;
    import flash.utils.ByteArray;
    
    var imgBytes:ByteArray = PNGEncoder.encode(bmd);
    var docsDir:File = File.documentsDirectory;
    try
    {
        docsDir.browseForSave("Save As");
        docsDir.addEventListener(Event.SELECT, saveData);
    }
    catch (error:Error)
    {
        trace("Failed:", error.message);
    }
    
    function saveData(event:Event):void 
    {
        var newFile:File = event.target as File;
        if (!newFile.exists) // remove this 'if' if overwrite is OK.
        {
            var stream:FileStream = new FileStream();
            stream.open(newFile, FileMode.WRITE);
            stream.writeBytes(imgBytes);
            stream.close();
        } 
        else trace('Selected path already exists.');
    }
    

    The manual is always your friend :)

    BTW, I see you're relatively new here - welcome to StackExchange! If you find my answer helpful, please be sure to select it as the answer.