When I run this code, the file is written successfully, but none of the events fire (or is the process happneing so quickly to the point that they do not appear). Any help would be appreciated.
import flash.net.FileReference;
import flash.filesystem.*;
var myFile:File = File.documentsDirectory.resolvePath("AIR Test/test.txt");
var myFileStream:FileStream = new FileStream();
myFileStream.addEventListener(Event.COMPLETE, completeHandler);
myFileStream.addEventListener(ProgressEvent.PROGRESS, progressHandler);
myFileStream.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
myFileStream.openAsync(myFile, FileMode.WRITE);
myFileStream.writeUTFBytes("Hello world");
function completeHandler(event:Event):void {
// ...
trace("Complete")
}
function progressHandler(event:ProgressEvent):void {
// ...
trace("Progress")
}
function errorHandler(event:IOErrorEvent):void {
// ...
trace("Error")
}
You set the wrong events to what you want to do.
Instead of Event.COMPLETE
, use Event.CLOSE
to show that the process ended. Don't forget to add myFileStream.close()
to actually trigger the event.
Instead of ProgressEvent.PROGRESS
, use OutputProgressEvent.OUTPUT_PROGRESS
to display progress. You can call myFileStream.close()
from the OUTPUT_PROGRESS
-event, after the process is 100% respectively all bytes have been written (event.bytesPending == 0
).
Working example:
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.OutputProgressEvent;
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.net.FileReference;
var myFile: File = File.documentsDirectory.resolvePath("AIR Test/test.txt");
var myFileStream: FileStream = new FileStream();
myFileStream.openAsync(myFile, FileMode.WRITE);
myFileStream.addEventListener(Event.CLOSE, completeHandler);
myFileStream.addEventListener(OutputProgressEvent.OUTPUT_PROGRESS, progressHandler);
myFileStream.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
myFileStream.writeUTFBytes("Hello world");
function completeHandler(event: Event): void {
// ...
trace("Complete");
}
function progressHandler(event: OutputProgressEvent): void {
// ...
var progressRatio: Number = (1 - (event.bytesPending / event.bytesTotal));
trace(progressRatio);
trace("Progress");
if (event.bytesPending == 0) {
//All bytes have been written to the file. Close the FileStream to trigger Event.CLOSE
event.target.close();
}
}
function errorHandler(event: IOErrorEvent): void {
// ...
trace("Error");
}