且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Flex 中将文件转换为 ByteArray?

更新时间:2022-11-19 09:14:46

如果您的目标是 Flash Player 10,这应该可行:

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>

假设您首先加载文件——在本例中,加载操作发生在 creationComplete 上,并且字节存储在加载文件中——当用户单击保存图像"时,字节应该准备好保存.测试并验证了示例的工作原理.希望能帮到你!

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!