Friday, April 4, 2008

Copying and saving files to the desktop in an AIR app

Another thing I learned today was how to copy a file from one location to another -- while allowing the user to choose a location and name. This allows the user to select a photo in the App and save a high resolution version to their computer. Here is the class I wound up with:

package {
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.events.*;

public class FileSaver{
private var fileSaver:File;
private var fileName:String;
private var pathToFile:String;

public function FileSaver(){//empty constructor}
public function saveFile(_pathToFile:String,_fileName:String):void{
fileName = _fileName;
pathToFile = _pathToFile;
// point the browse to the desktop--the user can change it on their ow
fileSaver = File.desktopDirectory.resolvePath(fileName);
// once they select the location it calls saveData
fileSaver.addEventListener(Event.SELECT, saveData);
fileSaver.browseForSave("Choose the location to save the file");
}

private function saveData(evt:Event):void{
//first get the file to save
var copyFromFile:File =
File.applicationDirectory.resolvePath(pathToFile + fileName);
// now copy it to the location chosen above
copyFromFile.copyTo(fileSaver);
}

private function completeHandler(evt:Event):void {
//put something here so the user knows the file is saved
}
}

To use it, create an instance of the class and call the saveFile() method -- passing it the path to the file you want to copy and the name of the file itself. If you're using Shu (as mentioned in the post below) make sure that the path includes the Application directory as well.

One other thing I need to fix (and add to the class) is that if the user trys to save over an already exiting file, it crashes the app. It's too late tonight to fix that but it should be a bit easier now that I have the basics of the problem down...

No comments: