=================================
=================================
=================================
출처: http://stackoverflow.com/questions/9854165/is-it-possible-to-download-and-save-file-using-adobe-air
i made a flash air application for android and i need to download file and save to application local directory
Thanks in advance....
URLRequest and URLLoader will allow you to fetch some data from the internet, FileStream allows you to save it locally (FileReference if you want them to choose where to save it) as in
<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
creationComplete="windowedapplication1_creationCompleteHandler(event)">
<fx:Script>
<![CDATA[
import mx.events.FlexEvent;
protected function windowedapplication1_creationCompleteHandler(event:FlexEvent):void
{
// TODO Auto-generated method stub
var urlLoader:URLLoader = new URLLoader();
urlLoader.addEventListener(Event.COMPLETE, complete_handler);
urlLoader.dataFormat = URLLoaderDataFormat.BINARY;
urlLoader.load(new URLRequest("http://www.shaunhusain.com/CheckboxList/CheckboxList.swf"));
}
private function complete_handler(event:Event):void
{
var data:ByteArray = event.target.data;
var fr:FileReference = new FileReference();
fr.save(data, 'test.swf');
var fileStream:FileStream = new FileStream();
trace(File.applicationDirectory.nativePath);
fileStream.open(new File(File.applicationDirectory.nativePath+"\\test.swf"),FileMode.WRITE);
fileStream.writeBytes(data, 0, data.length);
}
]]>
</fx:Script>
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
</s:WindowedApplication>
EDIT: AS3 Mobile project version:
package
{
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.net.FileReference;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
import flash.utils.ByteArray;
public class DownloadFileMobileAS3 extends Sprite
{
public function DownloadFileMobileAS3()
{
super();
// support autoOrients
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
createLoader();
}
protected function createLoader():void
{
// TODO Auto-generated method stub
var urlLoader:URLLoader = new URLLoader();
urlLoader.addEventListener(Event.COMPLETE, complete_handler);
urlLoader.dataFormat = URLLoaderDataFormat.BINARY;
urlLoader.load(new URLRequest("http://www.shaunhusain.com/CheckboxList/CheckboxList.swf"));
}
private function complete_handler(event:Event):void
{
var data:ByteArray = event.target.data;
var fr:FileReference = new FileReference();
fr.save(data, 'test.swf');
var fileStream:FileStream = new FileStream();
trace("something");
trace(File.applicationDirectory);
trace(File.applicationDirectory.nativePath);
trace(File.applicationStorageDirectory.nativePath);
fileStream.open(new File(File.applicationStorageDirectory.nativePath+"\\test.swf"),FileMode.WRITE);
fileStream.writeBytes(data, 0, data.length);
}
}
}
I included both options in the code above you would want to either take out the file reference part or take out the file stream part otherwise it'll be saved twice.
I just added the mobile section, it in fact does have some sort of dialog it prompts you with for saving a file on Android, though it's a dialog I've never seen before, just gives you the option of where to save it and Audio Files, Image Files, and Video Files as options or a default location at /mnt/sdcard/test.swf. I let it save there and am able to see it using ES Explorer (though I had no good way to verify the data was in tact it appears generally to be correct). The one using the applicationDirectory was failing on me, tracing it out I was seeing no nativePath so I switched it to applicationStorageDirectory which had a value and it seems to have saved without error, unfortunately it's in my root /data folder and since I don't have my phone rooted I have no way to completely confirm the file is actually there but no errors. Let me know if you've tried this and what specific issues you're still encountering.
Thanks for helping he but i am using this code for flash i had done everything to make suit for flash but not worked.If you know how to make suit this code for flash please help.. – Pabo Koha Mar 25 '12 at 7:45
Hey Pabo, aside from the application as the container and using the creation complete event I don't think I'm really depending on anything in Flex for this to work, it should all be available in Flash... I'll make a flash mobile project and throw it in there to see if I get any issues, the only thing I could think of that may be a problem is using the file reference since I don't know how that works on mobile platforms, generally it's requesting a OS specific pop-up for selecting a file or a location to save but there is no built-in file system browser I'm aware of on Android or iOS. – shaunhusain Mar 25 '12 at 23:26
I updated my answer, also to note I checked allow writing to external storage when creating the project so it would add that to the -app.xml file and ultimately the apk installed on the device. – shaunhusain Mar 26 '12 at
shaunhusain, really thanks for helping.Your code worked on my android phone. But the problem is i am making a magazine application when person click on update button the image need to be download automatically with out asking the location where the files need to be save.Your code is great i couldn't done this much yet but problem is i don't want that dialog box where the file need to save.If know how do that please help.Thanks a lot for help me – Pabo Koha Mar 26 '12 at 8:42
If you remove the FileReference part the user won't be prompted, the next step then is to determine how to save the file where you want to save it, are you going for saving it directly to a pictures folder or otherwise where, basically you can use the FileStream to save where-ever without prompting the user, however you just need to figure out how to get what that path is using the File classes static properties (most likely). So what's the specific folder you want to save the data into? – shaunhusain Mar 26 '12 at 16:00
=================================
=================================
=================================
Hi.
I am stumbling at some security errors being thrown at me.
I have two .swf files both made by me (thus they both can be edited). First is gameShell.swf (it is an AIR app), the second is game.swf (regular swf that has to be downloaded and addChilded).
AIR application has to download an .swf file to the app-storage:
var file:File = new File("app-storage:/" + fileLoader.fileName);
var fileStream:FileStream = new FileStream();
fileStream.open(file, FileMode.WRITE);
fileStream.writeBytes(fileLoader.data);
fileStream.close();
and then add it as a child. This child has to be in a different application domain in order not to intersect with parent classes:
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, gameLoadedHandler, false, 0, true);
var context:LoaderContext = new LoaderContext();
context.applicationDomain = new ApplicationDomain();
loader.load(new URLRequest("app-storage:/" + "game.swf"), context);
This game.swf has to be able to access the stage. Here come troubles. The first error I get is when trying to access the stage:
SecurityError: Error #2070: Security sandbox violation: caller app-storage:/game.swf cannot access Stage owned by app:/gameShell.swf.
Trying to:
Security.allowDomain("*");
yields:
SecurityError: Error #3207: Application-sandbox content cannot access this feature.
Trying to:
var context:LoaderContext = new LoaderContext();
context.applicationDomain = new ApplicationDomain();
context.securityDomain = SecurityDomain.currentDomain;
yields:
SecurityError: Error #2142: Security sandbox violation: local SWF files cannot use the LoaderContext.securityDomain property. app:/gameShell.swf was attempting to load app-storage:/game.swf.
Trying in gameShell.swf:
loaderInfo.childSandboxBridge = {stage:stage};
and in game.swf:
public static function getStage():Stage {
return (Security.sandboxType == Security.APPLICATION) ? instance.parent.loaderInfo.childSandboxBridge.stage : instance.stage;
}
yields:
SecurityError: Error #2070: Security sandbox violation: caller app-storage:/game.swf cannot access Stage owned by app:/gameShell.swf.
Eww…….
How do I do that?
Thank you!
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
you can’t. you can, however, provide functions that permit adding things to the stage, removing them, etc. but the other SWF can never actually interact with them, iirc
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
If the problem with the method that caused Error #2142 is that the SWF is local, perhaps you should try loading it back into a ByteArray and calling Loader.loadBytes().
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Thank you. Loading it back into a ByteArray and calling Loader.loadBytes() did the trick. I guess it is because the loaded swf from bytes is considered to be as in the same domain as the calling swf, so no security violation occurs. Many thanks.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Originally posted by BrainStormer:
Thank you. Loading it back into a ByteArray and calling Loader.loadBytes() did the trick. I guess it is because the loaded swf from bytes is considered to be as in the same domain as the calling swf, so no security violation occurs. Many thanks.
they’re in the same domain, it’s just different sandboxes: the AIR app must be protected from potentially malicious(or even viral) code being introduced by a loadedSWF. due to the nature of file systems and the API to access them in general, you can’t be certain the loaded SWF is indeed your own code, even if you just wrote it to file. while unlikely this will be a problem for you, it is good to be aware of
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
I’m having a very similar problem. I have an Air application and I’m trying to load and display a swf within it.
I use
var swfloader:SWFLoader = new SWFLoader();
swfloader.loaderContext = lc;
swfloader.percentHeight = 100;
swfloader.percentWidth = 100;
swfloader.loadForCompatibility = true;
swfloader.load(file.nativePath);
I have also tried loading it as a ByteArray but I get this error
TypeError: Error #1007: Instantiation attempted on a non-constructor.
at mx.preloaders::Preloader/initialize()[E:\dev\4.y\frameworks\projects\framework\src\mx\preloaders\Preloader.as:261]
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
You’re doing someting like new randomThing where randomThing isn’t a constructor.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
=================================
=================================
=================================
출처: http://www.cultcreative.com/tutorials/11/13/2011/local-file-access-editing-for-android-and-ios/
Recently, while building The Etiquette App in Flash Builder for both Android and iOS we decided that the best way to allow for data updates was to store the data files locally and intermittently check for updates on our server. If there is a data update, the app checks for a connection, loads the new data and completes the update as needed.
While trying to make this all work, we ran into a number of issues. The biggest issue was just accessing the files and making sure that the application was able to access files on both Android and iOS. We searched the web and were able to find things that worked for one mobile OS but not the other. It was a mind-numbing experience to say the least.
When working with mobile in Air, there are a couple of different directories that you have access to through your code. The main two that we are going to focus on are the applicationDirectory and the applicationStorageDirectory. What we discovered was that the applicationDirectory is read-only, which is unfortunate because that is where the files that you include with your application reside. You can’t have an app that updates the files that come with it.
As a bit of a workaround, we came up with a method that has worked quite well for us. That is to include the data files in the applicationDirectory and, on the first launch of the app, we copy them to the applicationStorageDirectory so that they are now workable. This does duplicate data, but it isn’t too much data and we wanted to make sure that data shipped with the app so we didn’t force users to be online while using it.
Below is a walk-through of how we accomplished this:
// check to see if the file exists in the applicationStorageDirectory if (!File.applicationStorageDirectory.resolvePath("data/filename.dat").exists) copyFile("filename.dat"); private function copyFile(ARG_file:String): void { // check to see if the file exists var file:File; file = File.applicationStorageDirectory.resolvePath("data/" + ARG_file); // if it doesn't exist if (!file.exists) { // get the file that we included with the application var originalFile:File; originalFile = File.applicationDirectory.resolvePath("data/" + ARG_file); // open and “READ” the content of the file var fileStream:FileStream = new FileStream(); fileStream.open(originalFile, FileMode.READ); var fileContent:String = fileStream.readUTF(); fileStream.close(); // create the new file var applicationStorageDirectoryPath:File = File.applicationStorageDirectory; var nativePathToApplicationStorageDirectory:String = applicationStorageDirectoryPath.nativePath.toString(); nativePathToApplicationStorageDirectory += "/data/" + ARG_file; file = new File(nativePathToApplicationStorageDirectory); // write the contents from the other file to the new file var writeStream:FileStream = new FileStream(); writeStream.open(file, FileMode.WRITE); writeStream.writeUTF(str); writeStream.close(); } } |
That code executes every time the application is loaded. From then on, we just use the file location in the applicationStorageDirectory to read the data from. When there is an update from the server, it just updates the new file. You can use the same code above to read the new file.
private function readFile(ARG_file:String):String { // get the file that we included with the application var file:File = File.applicationStorageDirectory.resolvePath("data/" + ARG_file); // open and “READ” the content of the file var fileStream:FileStream = new FileStream(); fileStream.open(originalFile, FileMode.READ); var fileContent:String = fileStream.readUTF(); fileStream.close(); return fileContent; } private function writeFile(ARG_file:String, ARG_content:String):void { // find the file var applicationStorageDirectoryPath:File = File.applicationStorageDirectory; var nativePathToApplicationStorageDirectory:String = applicationStorageDirectoryPath.nativePath.toString(); nativePathToApplicationStorageDirectory += "/data/" + ARG_file; file = new File(nativePathToApplicationStorageDirectory); // write the contents parameter var writeStream:FileStream = new FileStream(); writeStream.open(file, FileMode.WRITE); writeStream.writeUTF(ARG_content); writeStream.close(); } |
That’s it! You are now able to read and write files on both Android and iOS using Actionscript 3 in Air without difficulty.
Comments
=================================
=================================
=================================
Adobe AIR 1.0 and later
The File class extends the FileReference class. The FileReference class, which is available in Adobe® Flash® Player as well as AIR, represents a pointer to a file. The File class adds properties and methods that are not exposed in Flash Player (in a SWF file running in a browser), due to security considerations. About the File classYou can use the File class for the following:
A File object can point to the path of a file or directory that does not yet exist. You can use such a File object in creating a file or directory. Paths of File objectsEach File object has two properties that each define its path:The File class includes static properties for pointing to standard directories on Mac OS, Windows, and Linux. These properties include:
These properties have different values on different operating systems. For example, Mac and Windows each have a different native path to the user’s desktop directory. However, the File.desktopDirectory property points to an appropriate directory path on every platform. To write applications that work well across platforms, use these properties as the basis for referencing other directories and files used by the application. Then use the resolvePath() method to refine the path. For example, this code points to the preferences.xml file in the application storage directory: Although the File class lets you point to a specific file path, doing so can lead to applications that do not work across platforms. For example, the path C:\Documents and Settings\joe\ only works on Windows. For these reasons, it is best to use the static properties of the File class, such as File.documentsDirectory. The actual native paths for these directories vary based on the operating system and computer configuration. The paths shown in this table are typical examples. You should always use the appropriate static File class properties to refer to these directories so that your application works correctly on any platform. In an actual AIR application, the values for applicationID and filename shown in the table are taken from the application descriptor. If you specify a publisher ID in the application descriptor, then the publisher ID is appended to the application ID in these paths. The value for userName is the account name of the installing user. Pointing a File object to a directoryThere are different ways to set a File object to point to a directory.Pointing to the user’s home directoryYou can point a File object to the user’s home directory. The following code sets a File object to point to an AIR Test subdirectory of the home directory:Pointing to the user’s documents directoryYou can point a File object to the user's documents directory. The following code sets a File object to point to an AIR Test subdirectory of the documents directory:Pointing to the desktop directoryYou can point a File object to the desktop. The following code sets a File object to point to an AIR Test subdirectory of the desktop:Pointing to the application storage directoryYou can point a File object to the application storage directory. For every AIR application, there is a unique associated path that defines the application storage directory. This directory is unique to each application and user. You can use this directory to store user-specific, application-specific data (such as user data or preferences files). For example, the following code points a File object to a preferences file, prefs.xml, contained in the application storage directory:The application storage directory location is typically based on the user name and the application ID. The following file system locations are given here to help you debug your application. You should always use the File.applicationStorage property or app-storage: URI scheme to resolve files in this directory:
The URL (and url property) for a File object created with File.applicationStorageDirectory uses the app-storage URL scheme (see Supported AIR URL schemes), as in the following: Pointing to the application directoryYou can point a File object to the directory in which the application was installed, known as the application directory. You can reference this directory using the File.applicationDirectory property. You can use this directory to examine the application descriptor file or other resources installed with the application. For example, the following code points a File object to a directory named images in the application directory:The URL (and url property) for a File object created with File.applicationDirectory uses the app URL scheme (see Supported AIR URL schemes), as in the following: Note: On Android, the files in the application package are not accessible via the nativePath. The nativePath property is an empty string. Always use the URL to access files in the application directory rather than a native path. Pointing to the cache directoryYou can point a File object to the operating system’s temporary or cache directory using the File.cacheDirectory property. This directory contains temporary files that are not required for the application to run and will not cause problems or data loss for the user if they are deleted.In most operating systems the cache directory is a temporary directory. On iOS, the cache directory corresponds to the application library’s Caches directory. Files in this directory are not backed up to online storage, and can potentially be deleted by the operating system if the device’s available storage space is too low. For more information, see Controlling file backup and caching. Pointing to the file system rootThe File.getRootDirectories() method lists all root volumes, such as C: and mounted volumes, on a Windows computer. On Mac OS and Linux, this method always returns the unique root directory for the machine (the "/" directory). TheStorageVolumeInfo.getStorageVolumes() method provides more detailed information on mounted storage volumes (see Working with storage volumes).Note: The root of the file system is not readable on Android. A File object referencing the directory with the native path, “/”, is returned, but the properties of that object do not have accurate values. For example, spaceAvailable is always 0. Pointing to an explicit directoryYou can point the File object to an explicit directory by setting the nativePath property of the File object, as in the following example (on Windows):Important: Pointing to an explicit path this way can lead to code that does not work across platforms. For example, the previous example only works on Windows. You can use the static properties of the File object, such as File.applicationStorageDirectory, to locate a directory that works cross-platform. Then use the resolvePath() method (see the next section) to navigate to a relative path. Navigating to relative pathsYou can use the resolvePath() method to obtain a path relative to another given path. For example, the following code sets a File object to point to an "AIR Test" subdirectory of the user's home directory:You can also use the url property of a File object to point it to a directory based on a URL string, as in the following: For more information, see Modifying File paths. Letting the user browse to select a directoryThe File class includes the browseForDirectory() method, which presents a system dialog box in which the user can select a directory to assign to the object. The browseForDirectory() method is asynchronous. The File object dispatches a select event if the user selects a directory and clicks the Open button, or it dispatches a cancel event if the user clicks the Cancel button.For example, the following code lets the user select a directory and outputs the directory path upon selection: Note: On Android, the browseForDirectory() method is not supported. Calling this method has no effect; a cancel event is dispatched immediately. To allow users to select a directory, use a custom, application-defined dialog, instead. Pointing to the directory from which the application was invokedYou can get the directory location from which an application is invoked, by checking the currentDirectory property of the InvokeEvent object dispatched when the application is invoked. For details, see Capturing command line arguments.Pointing a File object to a fileThere are different ways to set the file to which a File object points.Pointing to an explicit file pathImportant: Pointing to an explicit path can lead to code that does not work across platforms. For example, the path C:/foo.txt only works on Windows. You can use the static properties of the File object, such as File.applicationStorageDirectory, to locate a directory that works cross-platform. Then use the resolvePath() method (see Modifying File paths) to navigate to a relative path.You can use the url property of a File object to point it to a file or directory based on a URL string, as in the following: You can also pass the URL to the File() constructor function, as in the following: The url property always returns the URI-encoded version of the URL (for example, blank spaces are replaced with "%20): You can also use the nativePath property of a File object to set an explicit path. For example, the following code, when run on a Windows computer, sets a File object to the test.txt file in the AIR Test subdirectory of the C: drive: You can also pass this path to the File() constructor function, as in the following: Use the forward slash (/) character as the path delimiter for the nativePath property. On Windows, you can also use the backslash (\) character, but doing so leads to applications that do not work across platforms. For more information, see Modifying File paths. Enumerating files in a directoryYou can use the getDirectoryListing() method of a File object to get an array of File objects pointing to files and subdirectories at the root level of a directory. For more information, see Enumerating directories.Letting the user browse to select a fileThe File class includes the following methods that present a system dialog box in which the user can select a file to assign to the object:
For example, the following code presents the user with an “Open” dialog box in which the user can select a file: If the application has another browser dialog box open when you call a browse method, the runtime throws an Error exception. Note: On Android, only image, video, and audio files can be selected with the browseForOpen() and browseForOpenMultiple() methods. The browseForSave() dialog also displays only media files even though the user can enter an arbitrary filename. For opening and saving non-media files, you should consider using custom dialogs instead of these methods. Modifying File pathsYou can also modify the path of an existing File object by calling the resolvePath() method or by modifying the nativePath or url property of the object, as in the following examples (on Windows):When using the nativePath property, use the forward slash (/) character as the directory separator character. On Windows, you can use the backslash (\) character as well, but you should not do so, as it leads to code that does not work cross-platform. Supported AIR URL schemesIn AIR, you can use any of the following URL schemes in defining the url property of a File object:Controlling file backup and cachingCertain operating systems, most notably iOS and Mac OS X, provide users the ability to automatically back up application files to a remote storage. In addition, on iOS there are restrictions on whether files can be backed up and also where files of different purposes can be stored.The following summarize how to comply with Apple’s guidelines for file backup and storage. For further information see the next sections.
In order to save backup space and reduce network bandwidth use, Apple’s guidelines for iOS and Mac applications specify that only files that contain user-entered data or data that otherwise can’t be regenerated or re-downloaded should be designated for backup. By default all files in the application library folders are backed up. On Mac OS X this is the application storage directory. On iOS, this includes the application storage directory, the application directory, the desktop directory, documents directory, and user directory (because those directories are mapped to application library folders on iOS). Consequently, any files in those directories are backed up to server storage by default. If you are saving a file in one of those locations that can be re-created by your application, you should flag the file so the operating system knows not to back it up. To indicate that a file should not be backed up, set the File object’s preventBackup property to true. Note that on iOS, for a file in any of the application library folders, even if the file’s preventBackup property is set to true the file is flagged as a persistent file that the operating system shouldn’t delete. Controlling file caching and deletion Apple’s guidelines for iOS applications specify that as much as possible, content that can be regenerated should be made available to the operating system to delete in case the device runs low on storage space. On iOS, files in the application library folders (such as the application storage directory or the documents directory) are flagged as permanent and are not deleted by the operating system. Save files that can be regenerated by the application and are safe to delete in case of low storage space in the application cache directory. You access the cache directory using the File.cacheDirectory static property. On iOS the cache directory corresponds to the application’s cache directory (<Application Home>/Library/Caches). On other operating systems, this directory is mapped to a comparable directory. For example, on Mac OS X it also maps to the Caches directory in the application library. On Android the cache directory maps to the application’s cache directory. On Windows, the cache directory maps to the operating system temp directory. On both Android and Windows, this is the same directory that is accessed by a call to the File class’s createTempDirectory() and createTempFile() methods. Finding the relative path between two filesYou can use the getRelativePath() method to find the relative path between two files:The second parameter of the getRelativePath() method, the useDotDot parameter, allows for .. syntax to be returned in results, to indicate parent directories: Obtaining canonical versions of file namesFile and path names are not case sensitive on Windows and Mac OS. In the following, two File objects point to the same file:However, documents and directory names do include capitalization. For example, the following assumes that there is a folder named AIR Test in the documents directory, as in the following examples: The canonicalize() method converts the nativePath object to use the correct capitalization for the file or directory name. On case sensitive file systems (such as Linux), when multiple files exists with names differing only in case, the canonicalize() method adjusts the path to match the first file found (in an order determined by the file system). You can also use the canonicalize() method to convert short file names ("8.3" names) to long file names on Windows, as in the following examples: Working with packages and symbolic linksVarious operating systems support package files and symbolic link files:Packages—On Mac OS, directories can be designated as packages and show up in the Mac OS Finder as a single file rather than as a directory. Symbolic links—Mac OS, Linux, and Windows Vista support symbolic links. Symbolic links allow a file to point to another file or directory on disk. Although similar, symbolic links are not the same as aliases. An alias is always reported as a file (rather than a directory), and reading or writing to an alias or shortcut never affects the original file or directory that it points to. On the other hand, a symbolic link behaves exactly like the file or directory it points to. It can be reported as a file or a directory, and reading or writing to a symbolic link affects the file or directory that it points to, not the symbolic link itself. Additionally, on Windows the isSymbolicLink property for a File object referencing a junction point (used in the NTFS file system) is set to true. The File class includes the isPackage and isSymbolicLink properties for checking if a File object references a package or symbolic link. The following code iterates through the user’s desktop directory, listing subdirectories that are not packages: The following code iterates through the user’s desktop directory, listing files and directories that are not symbolic links: The canonicalize() method changes the path of a symbolic link to point to the file or directory to which the link refers. The following code iterates through the user’s desktop directory, and reports the paths referenced by files that are symbolic links: Determining space available on a volumeThe spaceAvailable property of a File object is the space available for use at the File location, in bytes. For example, the following code checks the space available in the application storage directory:If the File object references a directory, the spaceAvailable property indicates the space in the directory that files can use. If the File object references a file, the spaceAvailable property indicates the space into which the file could grow. If the file location does not exist, the spaceAvailable property is set to 0. If the File object references a symbolic link, the spaceAvailable property is set to space available at the location the symbolic link points to. Typically the space available for a directory or file is the same as the space available on the volume containing the directory or file. However, space available can take into account quotas and per-directory limits. Adding a file or directory to a volume generally requires more space than the actual size of the file or the size of the contents of the directory. For example, the operating system may require more space to store index information. Or the disk sectors required may use additional space. Also, available space changes dynamically. So, you cannot expect to allocate all of the reported space for file storage. For information on writing to the file system, see Reading and writing files. The StorageVolumeInfo.getStorageVolumes() method provides more detailed information on mounted storage volumes (see Working with storage volumes). Opening files with the default system applicationIn AIR 2, you can open a file using the application registered by the operating system to open it. For example, an AIR application can open a DOC file with the application registered to open it. Use the openWithDefaultApplication() method of a File object to open the file. For example, the following code opens a file named test.doc on the user’s desktop and opens it with the default application for DOC files:Note: On Linux, the file’s MIME type, not the filename extension, determines the default application for a file. The following code lets the user navigate to an mp3 file and open it in the default application for playing mp3 files: You cannot use the openWithDefaultApplication() method with files located in the application directory. AIR prevents you from using the openWithDefaultApplication() method to open certain files. On Windows, AIR prevents you from opening files that have certain filetypes, such as EXE or BAT. On Mac OS and Linux, AIR prevents you from opening files that will launch in certain application. (These include Terminal and AppletLauncher on Mac OS; and csh, bash, or ruby on Linux.) Attempting to open one of these files using the openWithDefaultApplication() method results in an exception. For a complete list of prevented filetypes, see the language reference entry for the File.openWithDefaultApplication() method. |
=================================
=================================
=================================
I have a Flex application (SDK 4.5.1) which runs on iPad... I need to download any files, put them in local directory (like the File.applicationStorageDirectory) and then view the file inside my application.
So in my test application a downloaded a png image using the urlLoader class.
Here it is the complete handler of the download:
private function onComplete3(event:Event):void{
try{
var ba:ByteArray = event.target.data as ByteArray;
var file:File=File.applicationStorageDirectory.resolvePath("img.png");
var pathFile:String = file.nativePath;
var fileStream:FileStream = new FileStream();
fileStream.open(file, FileMode.WRITE);
fileStream.writeBytes(ba);
fileStream.addEventListener(Event.CLOSE, fileClosed);
fileStream.addEventListener(IOErrorEvent.IO_ERROR,function(e:IOErrorEvent):void{
status0.text = "STATE : ERROR 3"
});
fileStream.close();
status0.text = "STATO : OK";
path0.text = pathFile;
immagine0.source = pathFile;
catch(e:Error){
status0.text = "STATE : ERROR 2"
}
}
On my iPad I can see the downloaded file exists, but when I run the line immagine0.source = pathFile (which is an image component), nothing appears... Maybe I can write a file but I cannot read it?
After 6 hours of debug and coding...i solved this problem with a very simple solution... changed the line
var pathFile:String = file.nativePath;
with
var pathFile:String = file.url;
He solved the file.url in this way:
app-storage:/img.png
.Now it works! Hope this post will be helpful for someone other have this problem..Thanks to all
The following 2 functions are to write and read file in Flex 4.5.
protected function button1_clickHandler(event:MouseEvent):void
{
var file:File = File.applicationStorageDirectory.resolvePath("samples/test.txt");
var stream:FileStream = new FileStream()
stream.open(file, FileMode.WRITE);
stream.writeUTFBytes(contents.text);
stream.close();
}
protected function button2_clickHandler(event:MouseEvent):void
{
var file:File = File.applicationStorageDirectory.resolvePath("samples/test.txt");
var stream:FileStream = new FileStream()
stream.open(file, FileMode.READ);
results.text = stream.readUTFBytes(stream.bytesAvailable);
stream.close();
}
=================================
=================================
=================================
Francesco
thank you for the post! I’m trying to handle a local file in a Flex application for iOS devices.
I tried to use the way you suggested:
var image:File = File.applicationDirectory.resolvePath(“data/res.png”);
If I put the images in the src folder, after building with Flash Builder, I can use them with File.applicationDirectory.resolvePath(“image.png”).
William
file.copyTo(tempFile);
tempFile.openWithDefaultApplication();
var source:String;
source = buildPath + “/file_name.pdf”;
var file:File = new File(source);try {
file.copyTo(destination, true);//I also tried file.moveTo(destination, true);
destination.openWithDefaultApplication();
debug_txt.appendText(destination.url + ‘\n’);
}
catch (error:Error) {
trace(“Error:” + error.message);
debug_txt.appendText(‘Error = ‘ + error + ‘\n’);
}I am wondering if I have to create a temp directory?
destination = destination.resolvePath(“adamzucchi_resume.pdf”);
var source:String;
source = buildPath + “/file_name.pdf”;
var file:File = new File(source);
var tempFile:File();
file.copyTo(tempFile);
tempFile.openWithDefaultApplication();
}
catch (error:Error) {
trace(“Error:” + error.message);
}
var source:String;
source = buildPath + “/file_name.pdf”;
var file:File = new File(source);try {file.copyTo(newFile);//I also tried file.moveTo(destination, true);
newFile.openWithDefaultApplication();
debug_txt.appendText(newFile.url + ‘\n’);
}
catch (error:Error) {
trace(“Error:” + error.message);
debug_txt.appendText(‘Error = ‘ + error + ‘\n’);
}
newfile = File.applicationStorageDirectory.resolvePath(“file_name.pdf”);
debug_txt.appendText(‘The file you are looking for does not exist in the application directory \n’);
return; // assuming you are using this in a function that would return void.
}
var nativePathToApplicationStorageDirectory:String = applicationStorageDirectoryPath.nativePath.toString();
nativePathToApplicationStorageDirectory += “filename.pdf”;
newFile = new File(nativePathToApplicationStorageDirectory);
file.copyTo(newFile);
newFile.openWithDefaultApplication();
var myXML:XML=new XML(e.target.data);
textBox1.text=myXML.sampleText1;Please let me know if you can offer any advice, Thanks
My Text