Save Text File in Flash


This page will explain how to save a text file to the users computer using ActionScript 3. Saving a text file to the local filesystem with Flash is easy to do. Starting with version 10, the Flash player now supports saving files to the users computer so you need to target that version or a later one to be able to save files locally using Flash.

The code bellow saves the text in tMessage to the users computer. The code opens a dialog box that lets the user save the file to the local file system.

var tFR:FileReference = new FileReference();
var tMessage:String = 'Hello World';, '.txt');

That is actually all the code you need. But lets explain what you can do with it. The class FileReference has a method called save with the following defenition.

public function save(data:*, defaultFileName:String = null):void 

data is the data to be saved. The data can be in one of several formats, and will be treated appropriately:

  • If the value is a String, it is saved as a UTF-8 text file.
  • If the value is XML, it is written to a text file in XML format, with all formatting preserved.
  • If the value is a ByteArray object, it is written to a data file verbatim.
  • If the value is null, the application throws an ArgumentError exception.
  • If the value is none of the above, the save() method calls the toString() method of the object to convert the data to a string, and it then saves the data as a text file. If that fails, the application throws an ArgumentError exception.

defaultFileName is the default filename displayed in the dialog box for the file to be saved. This parameter is optional.

The save() method first opens an dialog box that asks the user to enter a file name and select a location on the local computer to save the file. The save process begins when the user selects a location and confirms the save operation. Listeners receive events to indicate the progress. To ascertain the status of the dialog box and the save operation after calling save(), your code can listen for events such as cancel, open, progress, and complete.

That concludes this tutorial about how to save a text file in Flash using AS3. Learn more about Flash Builder 4.5 and the Flex framework in our other tutorials on this site.