views:

33

answers:

1

hey guys, i found a few scripts online and combined them to this. I want to download files from the web to my local harddrive. Any idea what i'm doing wrong?

var fs:FileStream;
var stream:URLStream;
var _output:Boolean = false;

init();
startDownload('http://www.teachenglishinasia.net/files/u2/purple_lotus_flower.jpg');

function init() { 
    stream = new URLStream();
    stream.addEventListener(ProgressEvent.PROGRESS, _dlProgressHandler); 
    stream.addEventListener(Event.COMPLETE, _dlCompleteHandler);
    stream.addEventListener(Event.OPEN, _dlStartHandler);
    fs = new FileStream();
    fs.addEventListener(OutputProgressEvent.OUTPUT_PROGRESS, _writeProgressHandler)
}

function startDownload(url:String):void {
     //fs.openAsync(lfile, FileMode.APPEND);
     _output = false;
     stream.load(new URLRequest(url));
}

function downloadComplete():void {
     var fileData:ByteArray = new ByteArray();
     stream.readBytes(fileData,0,stream.bytesAvailable);
     fs.writeBytes(fileData,0,fileData.length);
     fs.close(); 
}

function writeToDisk():void {
     _output = false;
     var fileData:ByteArray = new ByteArray();
     stream.readBytes(fileData,0,stream.bytesAvailable);
     fs.writeBytes(fileData,0,fileData.length);
}

function _dlProgressHandler(evt:ProgressEvent):void {
     if(_output){
         writeToDisk();   
     }
}

function _dlCompleteHandler(evt:Event):void { 
    downloadComplete();
} 

function _dlStartHandler(evt:Event):void {
     _output = true; 
}

function _writeProgressHandler(evt:OutputProgressEvent):void{
     _output = true;
}

Flash keeps telling me: Error: Error #2029: This URLStream object does not have a stream opened. However the connection to the webpage goes out.

Any ideas? Thank you for your help!

A: 

This is a long shot, since I've never worked with FileStream (and since the error message you pasted says 'this URLStream object etc'). But, It seems you FileStream object (fs) is not open and you are trying to 1) write to it and then 2) close it. My understanding is that any of those operations should throw an error if the file is not open. So, maybe it's worth cheking that. Other than that, can you paste a stack trace of the error, so it's more clear where it originates? (Tip: if you are compiling with the Flash IDE, check permit debugging in the actionscript settings; this will give you more verbose error messages and line numbers; this is of great help when debugging / troubleshooting).

Juan Pablo Califano