如何从URL中使用此代码下载文件数组

时间:2012-10-26 15:42:00

标签: flex air download mp3 resume-download

我正在努力使这段代码变得可恢复,并再次下载一个URL数组,但我正在努力。代码似乎只下载了最后一个文件但忽略了第一个文件。

<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" applicationComplete="init(event)" viewSourceURL="srcview/index.html">
    <mx:Script>
        <![CDATA[


            import flash.events.Event;
            import flash.events.ProgressEvent;
            import flash.net.URLRequest;
            import flash.net.URLStream;
            import flash.utils.ByteArray;
            import mx.controls.Alert;
            import mx.events.FlexEvent;

            //Declear variables
            private var urlStream:URLStream;
            private var fData:ByteArray;
            private var bytesLoaded:Number = 0;
            private var totalBytesLoaded:Number = 0;
            private var bytesTotal:Number = 0;
            private var fileName:String = "";
            private var file:File;
            private var fileStream:FileStream = new FileStream;

            //initialize even listeners
            protected function init(event:FlexEvent):void{
                urlStream = new URLStream;
                urlStream.addEventListener(ProgressEvent.PROGRESS, onProgress);
                urlStream.addEventListener(Event.COMPLETE, onComplete);


                var letters:Array = ["http://www.khanhvanweb.com/Music/Spanish Guitar Toni Braxton.mp3","http://dropthebeat.tv/audio/ToniBraxton-Please.mp3"];

                for (var i:int = 0; i < letters.length; i++) {
                    trace("Element " + i + ": " + letters[i]);
                    fileInput.text = letters[i];

                startDownload();
                }

            }

            //Start Downloaing

        //  if (fileInput.text = ""){


            public function startDownload():void{
                bytesLoaded = 0;
                bytesTotal = 0;
                totalBytesLoaded = 0;

                var url:String = fileInput.text;
                var index:int = url.lastIndexOf('/');
                fileName = url.substring(index+1, url.length);

                var str1:String = "/Music/ClassicalShop.Net/";

            //  file = File.documentsDirectory.resolvePath(fileName);
                //'Save to classical muic directory
                file = File.userDirectory.resolvePath(String(File.userDirectory.url + str1 + fileName));

                status = file.url;

                if(file.exists) {
                    btn.label = 'Download';
                    mx.controls.Alert.show('Please remove "'+fileName+'" from your disk', 'File with the same name already exists');
                    return;
                }

                output.text += 'Downloading\n';

                urlStream.load( new URLRequest(url) );
                fData = new ByteArray;
                fileInput.enabled = false;

                fileStream.open(file, file.exists ? FileMode.APPEND:FileMode.WRITE); }


        //  }




            private function pauseDownload():void {
                output.text += 'Downloading is paused\n';
                if(urlStream.connected) {
                    fData.clear();
                    urlStream.readBytes(fData, fData.length);
                    urlStream.close();
                    fileStream.writeBytes(fData);

                    }

                fileStream.close();

                totalBytesLoaded += bytesLoaded;
                trace( "pause size:"+ totalBytesLoaded);

                }



            //Resume the Download
            private function resumeDownload():void {
                output.text += 'Downloading \n';
                output.text +='bytes='+totalBytesLoaded+'-'+bytesTotal + '\n';
                var header0:URLRequestHeader = new URLRequestHeader('range', 'bytes='+totalBytesLoaded+'-'+bytesTotal);

                var request:URLRequest = new URLRequest(fileInput.text);
                request.requestHeaders.push(header0);

                urlStream.load( request );

                fileStream.open(file, file.exists ? FileMode.APPEND:FileMode.WRITE);
                }

            //Set progress of the file download
            private function onProgress(event:ProgressEvent):void {
                bytesLoaded = event.bytesLoaded;
                if(bytesTotal == 0)
                    bytesTotal = event.bytesTotal;

                trace( "size:"+ bytesLoaded);

                progressBar.setProgress( (totalBytesLoaded + event.bytesLoaded) / bytesTotal, progressBar.maximum);

                if(urlStream.bytesAvailable == 0) return;
                if(urlStream.connected)
                    {
                    fData.clear();
                    urlStream.readBytes(fData, fData.length);
                    fileStream.writeBytes(fData);

                    }
                }

            //Action to take when the file has completed downloading
            private function onComplete(event:Event):void
                {
                output.text += 'Download complete\n';
                bytesLoaded = 0;
                bytesTotal = 0;
                totalBytesLoaded = 0;
                progressBar.setProgress(0, 1);

                if(urlStream.connected)
                    {
                    fData.clear();
                    urlStream.readBytes(fData, fData.length);
                    urlStream.close();
                    fileStream.writeBytes(fData);
                    }

                fileInput.enabled = true;
                btn.label = 'Download';
                fData = null;

                fileStream.close();

                System.gc();
                }


            //write the file to disk
            private function writeFile():void
                {


                output.text += 'Saving File\n';
                var fileStream:FileStream = new FileStream;
                fileStream.open(file, file.exists ? FileMode.APPEND:FileMode.WRITE);
                fileStream.writeBytes(fData);
                fileStream.close();
                output.text += 'File Saved\n';


                }


            private function btnClickHandler():void
                {

                if(bytesLoaded == 0)
                    {
                    btn.label = 'Pause';


                    startDownload();
                    }
                    else
                        {
                        if(urlStream.connected)
                            {
                            btn.label = 'Resume';
                            pauseDownload();
                            }
                            else
                                {
                                btn.label = 'Pause';
        resumeDownload();
    }}}
        ]]>
    </mx:Script>
    <mx:TextInput id="fileInput" y="15" left="67" right="10"/>
    <mx:Button id="btn" x="286" y="65" label="Download" click="btnClickHandler()"/>
    <mx:ProgressBar id="progressBar" x="67" y="65" 
                    mode="manual" minimum="0" maximum="1" label="Downloading %3%%"/>
    <mx:Label x="10" y="20" text="File URL"/>
    <mx:TextArea id="output" left="10" right="10" top="107" bottom="10"/>
    <mx:Button y="65" label="Clear Input" right="10" 
               enabled="{fileInput.text.length==0 ? false:fileInput.enabled}"
               click="fileInput.text = ''"/>
    <mx:Label x="67" y="46" 
              text="http://www.example.com/downloads/episode77.mp3" 
              color="#878787"/>
</mx:WindowedApplication>

2 个答案:

答案 0 :(得分:0)

这是因为您正在使用全局变量。当您启动新的URLLoader / URLStream时,它会关闭之前的所有请求并从新请求开始。解决方案很简单。

public function startDownload( urlRequest:URLRequest ):void{
    var loader:URLLoader = new URLLoader();
    loader.load( urlRequest );
}

显然这只是基础知识,你需要添加其余的代码,但是你明白了。对于每个单独的文件,您需要一个完全独立的URLRequest和URLLoader / URLStream,因此您必须在函数范围内创建它们,而不是全局范围。

如果您需要在COMPLETE或PROGRESS事件中获取URLLoader,请查看event.currentTarget和event.Target。

如果您不希望它们同时运行,您可以在COMPLETE处理程序中手动增加一个“count”变量,并使用该count属性来获取数组中的下一个项目。

答案 1 :(得分:0)

我不确定您是否尝试使用移动平台,但我们刚刚在Android上发布了我们的新的原生扩展,这是一个可恢复的多部分下载管理器。在这里查看:http://myappsnippet.com/download-manager-air-native-extension/