From URLLoader to FileStream (or vice versa)

929 Views Asked by At

I have a functionality working with a file hardcoded through URL Loader, but I want to be able to select the file from anywhere on my harddrive in an Air application.

    public function loadFile(): Array {
        csv = new URLLoader();
        csv.addEventListener(Event.COMPLETE, completeHandler);
        csv.load(new URLRequest('carelinksample.csv'));
        return results;
    }

and completeHandler of course puts the data from the URLRequest into an array how I need it. But I want to replace the new URLRequest with some kind of Filestream command (or something else perhaps if there's another way to select local files with Air).

I have this code to load a local file, but I'm not totally sure what to do with it to get it to work with what I have in the URLLoader

private var filetype:FileFilter = new FileFilter("CSV Files(*.csv)","*.csv");           

public function chooseFile(event:MouseEvent):void {
                var f:File = File.desktopDirectory;
                f.browseForOpen("Select file to open", [filetype]);
                f.addEventListener(Event.SELECT, function (event:Event):void {
                    var fs:FileStream = new FileStream();
                    fs.open(event.target as File, FileMode.READ);
                    fs.close();
                });
1

There are 1 best solutions below

0
On BEST ANSWER

This code should do what you need:

private var _ref : FileReference;    
private function browse() {
    _ref = new FileReference();
    _ref.addEventListener(Event.SELECT, onSelect);
    _ref.browse([new FileFilter("CSV File", "*.csv")]);
}

private function onSelect(event : Event) : void {
    _ref.addEventListener(Event.COMPLETE, onData);
    _ref.load();
}

private function onData(event : Event) : void {
    parse(_ref.data.readUTFBytes(_ref.data.bytesAvailable));
}

private function parse(data : String) : void {

}