How to convert a file to a ByteArray in Flex

apache-flexfile-io

I was wondering how to convert a file I have on my server (pdf/excel/ppt) to a ByteArray. The reason I want to do this is to display the dialogue open/save as to the user and I must set the Content-Type to octet-stream. The dialogue shows fine with just navigateToURL() but for pdf's it is the user's local browser setting. For a URLRequest I must set the data as a ByteArray. I'm trying to use the code located here:

Custom printing with Flex

Best Answer

Provided you're targeting Flash Player 10, this should work:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="loadFile()">

    <mx:Script>
        <![CDATA[

            private var loadedFile:ByteArray;

            private function loadFile():void
            {
                var request:URLRequest = new URLRequest("http://test.enunciato.org/sample.pdf");
                var urlLoader:URLLoader = new URLLoader(request);

                urlLoader.addEventListener(Event.COMPLETE, onURLLoaderComplete);
                urlLoader.dataFormat = URLLoaderDataFormat.BINARY;
                urlLoader.load(request);
            }

            private function onURLLoaderComplete(event:Event):void
            {
                loadedFile = event.target.data;
            }

            private function saveLoadedFile():void
            {
                var file:FileReference = new FileReference();
                file.save(loadedFile, "SampleDoc.PDF"); 
            }

        ]]>
    </mx:Script>

    <mx:Button label="Save Image" horizontalCenter="0" verticalCenter="0" click="saveLoadedFile()" />

</mx:Application>

Assuming you load the file first -- in this example, the load operation happens on creationComplete, and the bytes get stored off in loadedFile -- the bytes should be and ready for saving when the user clicks Save Image. Tested and verified the example works. Hope it helps!