对于闪存:
要使用 Flash 在本地保存数据,您可以使用以下 3 种方式之一:Flash Player 缓存、SharedObject 或 FileReference 对象。对于您的本地文件,请忘记 PHP 和 MySQL,因为我们只谈论您获得的数据(json、xml、txt、...)。
- Flash Player 缓存:
您应该知道,默认情况下,Flash 播放器会将您文件的本地副本放在其缓存中。您可以将此本地副本用作数据的脱机源,但不要忘记,flash player 没有保存远程文件的最后一个版本,而是第一个版本,http://www.example.com/data.php 甚至与http://www.example.com/data.php?123 不同如果是同一个文件!有关这方面的更多详细信息,请查看my answer of this question。
- 共享对象:
我不知道您加载数据的大小,但正如 Adobe 所说的 SharedObject :
...用于在用户计算机上读取和存储有限数量的数据...
我认为它不用于大文件,不建议存储文件,而是存储一些简单的数据。当然,SharedOject作为浏览器的cookie,需要用户授权才能将数据写入硬盘,用户可以随时删除。
- 文件参考:
我认为这是完成您正在寻找的事情的最佳方式。您应该知道,要使用 FileReference 保存文件,您的用户会被邀请选择一个文件来保存数据并再次读取它。因此,如果您不希望任何用户与您的应用程序交互,请忘记这种方式。
文件引用使用示例:
var local_file_name:String = 'local.data',
file:FileReference = new FileReference(),
local_file_filter:FileFilter = new FileFilter('local data file', '*.data'),
remote_data_url:String = 'http://www.example.com/data.php',
url_request:URLRequest,
url_loader:URLLoader,
connected:Boolean = true;
if(connected){
get_remote_data();
} else {
get_local_data();
}
function get_remote_data(): void {
//we use a param to be sure that we have always the last version of our file
url_request = new URLRequest(remote_data_url + ('?' + new Date().getTime()));
url_loader = new URLLoader();
url_loader.addEventListener(Event.COMPLETE, on_data_loaded);
url_loader.load(url_request);
}
function get_local_data(): void {
// show the select dialog to the user to select the local data file
file.browse([local_file_filter]);
file.addEventListener(Event.SELECT, on_file_selected);
}
function on_data_loaded(e:Event): void {
var data:String = e.target.data;
// if the remote data is successfully loaded, save it on a local file
if(connected){
// show the save dialog and save data to a local file
file.save(data, local_file_name);
}
// use your loaded data
trace(data);
}
function on_file_selected(e:Event): void {
file.addEventListener(Event.COMPLETE, on_data_loaded);
file.load();
}
这段代码每次都会向用户显示一个保存对话框,当然,这只是一个示例,您必须根据需要对其进行调整...
编辑
对于空气:
使用 AIR,我们不需要 FileReference 对象,而是使用 File 和 FileStream 对象来保存数据:
// for example, our local file will be saved in the same dir of our AIR app
var file:File = new File( File.applicationDirectory.resolvePath('local.data').nativePath ),
remote_data_url:String = 'http://www.example.com/data.php',
data_url:String = remote_data_url,
url_request:URLRequest,
url_loader:URLLoader,
connected:Boolean = true;
if(!connected){
// if we are not connected, we use the path of the local file
data_url = file.nativePath;
}
load_data();
function load_data(): void {
url_request = new URLRequest(data_url);
url_loader = new URLLoader();
url_loader.addEventListener(Event.COMPLETE, on_data_loaded);
url_loader.load(url_request);
}
function on_data_loaded(e:Event): void {
var data:String = e.target.data;
if(connected){
// save data to the local file
var file_stream:FileStream = new FileStream();
file_stream.open(file, FileMode.WRITE);
file_stream.writeUTFBytes(data);
file_stream.close();
}
trace(data);
}
希望能有所帮助。