상세 컨텐츠

본문 제목

디바이스 모바일 air actionscript FILE 읽기 쓰기 보안 관련...

ADOBE/ ActionScript

by AlrepondTech 2020. 9. 23. 03:41

본문

반응형

 

 

 

 

=================================

=================================

=================================

 

 

 

 

 

 

 

 

출처: 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

  • FRANCESCONov 21, 2011but the method image.exists returns FALSE.Can you help me to place the file in the right way?
  • Thank you in advance,
    Francesco
  • The file path is {FLEX_PROJECT_FOLDER}/data/res.png and the class that use it is placed in {FLEX_PROJECT_FOLDER}/views/View.mxml
  • Hi,
    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”);
  • CULTCREATIVENov 21, 2011FRANCESCONov 23, 2011
  • Thank you for the support!
    If I put the images in the src folder, after building with Flash Builder, I can use them with File.applicationDirectory.resolvePath(“image.png”). 
  • the “data” folder needs to be in the /bin (or bin-release/bin-debug) folder. I generally just add the data folder to my /src folder so that it gets added to the build in Flash Builder no matter where it is building to. does that make sense?
  • WILLIAMDec 23, 2011Regards,
    William
  • Hey, I am getting an error on line 31, the (str) is undefined…any idea what I need to set this as?
  • CULTCREATIVEDec 23, 2011ADAMJan 14, 2012Thanks.
  • Adam
  • I am attempting to load a local PDF document in my application in AIR 3.1 for iOS. I have only been able to get the file to load using the StageWebView class,however I really want it to open in the native application on the device, such as Adobe Reader, or even the web browser. The PDF has to be local, so putting the file up on a server is not an option for me. I have used your example above to copy the file to my Application Storage Directory, however I am getting an error when it attempts to load the copied file, “The file “file_name.pdf” could not be opened. It may be damaged or use a file format that Preview doesn’t recognize.” I am seeing the file show up in the application storage directory when running this on my computer and it even opens the correct program called Preview. The method I am using on the file class to open the file is openWithDefaultApplication(). When I put the .ipa over to my device I am tracing out the location in a debug text field I put on the stage and it looks correct, however it doesn’t switch to the reader application. So I am wondering if my copy is broke on the device as it also is on my computer. Any input/advice on this would be greatly appreciated.
  • Hey, sorry about that, i think that it should be writeStream.writeUTF(fileContent);
  • CULTCREATIVEJan 14, 2012var tempFile:File;
    file.copyTo(tempFile);
    tempFile.openWithDefaultApplication();
  • I have a feeling that it might have something to do with where you are trying to open the file from. Adobe says: “You cannot use the openWithDefaultApplication() method with files located in the application directory.” (http://help.adobe.com/en_US/as3/dev/WS5b3ccc516d4fbf351e63e3d118666ade46-7fe4.html#WS2A7C0A31-A6A9-42d2-8772-79166A98A085), so you would have to copy it somewhere first. Try something like the following, where you create a duplicate instance and load that:
  • ADAMJan 15, 2012var buildPath:String = File.applicationDirectory.nativePath;
    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?
  • I attempted both a moveTo and a copyTo to the applicationStorageDirectory. Both of these work fine on my desktop, however when moving it to the iPad, I get two errors, one for each of the methods. The moveTo() throws the following error, Error #3001. The copyTo() throws the following error, Error #0.
  • var destination:File = File.applicationStorageDirectory;
    destination = destination.resolvePath(“adamzucchi_resume.pdf”);
  • So I went ahead and did something:
  • CULTCREATIVEJan 15, 2012var buildPath:String = File.applicationDirectory.nativePath;
    var source:String;
    source = buildPath + “/file_name.pdf”;
    var file:File = new File(source);
  • try {
    var tempFile:File();
    file.copyTo(tempFile);
    tempFile.openWithDefaultApplication();
    }
    catch (error:Error) {
    trace(“Error:” + error.message);
    }
  • what I think you should be doing is more along the lines of
  • ADAMJan 15, 2012Thanks again.
  • I should also mention that in my above post the strings that contain the file path were meant to be the same  They were when I compiled, I just didn’t know if it was necessary to leave the real filename in.
  • ADAMJan 15, 2012CULTCREATIVEJan 15, 2012ADAMJan 15, 2012CULTCREATIVEJan 15, 20121) are you sure you are including the pdf file in the package? are you getting a true value when you check if the original file exists while debugging on the device? if so move onto number 2.var buildPath:String = File.applicationDirectory.nativePath;
    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’);
    }
  • var newfile:File;
    newfile = File.applicationStorageDirectory.resolvePath(“file_name.pdf”);
  • if (!file.exists) {
    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.
    }
  • 2) This really should work, it is much like your original post
  • in that case, there are a couple other options that I can think of.
  • Sorry I should have mentioned that I had done that. I got a compiler error with what I copied and changed that constructor to fix that.
  • woops, sorry.. change var tempFile:File() to var tempFile:File = new File();
  • With your try/catch I am getting the following error: Error:Error #2037: Functions called in incorrect sequence, or earlier call was unsuccessful.
  • ADAMJan 15, 2012newFile = File.applicationStorageDirectory.resolvePath(‘/file_name.pdf’);
  • I am including the pdf, and I am getting that #0 error again (Error:Error #0). I have narrowed it down and it is breaking on this line:
  • CULTCREATIVEJan 15, 2012var applicationStorageDirectoryPath:File = File.applicationStorageDirectory;
    var nativePathToApplicationStorageDirectory:String = applicationStorageDirectoryPath.nativePath.toString();
    nativePathToApplicationStorageDirectory += “filename.pdf”;
    newFile = new File(nativePathToApplicationStorageDirectory);
    file.copyTo(newFile);
    newFile.openWithDefaultApplication();
  • the only thing that i could see being an issue with that is that you have an extra slash in your line, where mine is just the file name. You could also try the method that I used in the code above
  • ADAMJan 15, 2012ADAMJan 15, 2012ADAMJan 15, 2012ADAMJan 15, 2012Is this just not something we can call on iOS? I am compiling with AIR 3.1.
  • So I put it on the device and put a series of debug_txt traces in after each line in the try block and it is breaking on this: applicationStorageDirectoryPath.openWithDefaultApplication();
  • So here is the outcome. I have been able to get it to compile on my machine, and it opens with my default application, Preview, which is great. However after pushing this onto the device, I am getting that Error #0 in my debug_txt again. This applicationStorageDirectory is available when developing for iOS right?
  • So I nested in to where this applicationStorageDirectory actually is on my machine and deleted it, and now I can actually compile. I am wondering if something was corrupt in that? I will compile for the device and let you know how this goes  Thanks again for all the help, I really appreciate it.
  • I tried it both with and without the ‘/’ in front of the filename. I have incorporated the code in your last comment and it is breaking again on that first line:var applicationStorageDirectoryPath:File = File.applicationStorageDirectory;
  • JESSEFeb 2, 2012CULTCREATIVEFeb 6, 2012
  • Jesse, it shouldn’t matter what development environment you are using. I would assume that you should be able to open the PDF the same way that Adam and I have been working through. Give it a try and feel free to comment and let me know what happens. Take a look athttp://www.adobe.com/devnet/air/flex/articles/exploring_file_capabilities.htmlfor some reference with openWithDefaultApplication.
  • Adam! -Did you ever get this to work when publishing to AIR 3.1 for iOS, or did you give up?? Also, “cultcreative” I want to do what Adam is doing but, I do want to check against a .pdf on a server. I am using Flash CS5.5 to publish, not Flash Builder -is that a problem?
  • JAMES VANDERBILTFeb 22, 2012PAUL STEVENApr 17, 2012XSL ON XML TRANSFORM ISSUE OCCURS CLIENT SIDE ON ANDROID DEVICE « NIM REFLEXTIONSMay 9, 2012
  • [...] reading an item on the cultcreative blog site called Local File Access/ Editing for Android and IOS, I had modified the app so if there was no internet connection available, the app would still work [...]
  • Does your code create the “data” folder in the applicationsStorageDirectory if it doesn’t already exist?
  • I am trying to do this same thing on Android and am having problems. I’ve given up using openWithDefaultApplication(), since apparently you can do that on a file that is stored with your app. I’m trying a workaround where I copy the PDF to a temporary location and open it from there. But again, I’m having problems. The file appears to copy fine (no errors or events thrown), but the copy of the file doesn’t seem to actually get created. So when I do openWithDefaultApplication, I get a 3003 error or file/directory not found. This is on Android. Any ideas?
  • URLDec 14, 2012[...] Find More Informations here: cultcreative.com/tutorials/11/13/2011/local-file-access-editing-for-android-and-ios [...]…
  • … [Trackback]…
  • RAFADec 15, 2012CAIODec 18, 2012ADAM M.Feb 21, 2013Questions2. I figure your code is more of a starting point and not so much drop in and go, so to accomplish what i want, what more work do I add so I research that to do.AS3
    var myXML:XML=new XML(e.target.data);
    textBox1.text=myXML.sampleText1;Please let me know if you can offer any advice, Thanks
  • XML
    My Text
  • 3. And once i can get that app reading the file storage directory would the parsing be any different than how i do it from loading the XML by URL request. Like this.
  • 1. Where would i put the URL path to the file on my server.
  • Hello there. I’ve been doing Flash Pro for about two years now so I still consider myself a newbie. What i’m trying to accomplish is in my iOS app it calls to an XML file my server and displays the text in the text fields i have on stage. That parts simple. But now I want to store my current XML on the server to the applicationStorageDirectory for off line use. When I stumbled upon this tutorial i felt this is exactly what I’m looking for. How ever I can’t seem to get this to work. I never worked with the filesystem class before.
  • I’m trying the same problem, I wonder if they found a solution to this problem in android
  • Hi people. I hace done the same with an mp3 file and no problems I can listen perfectly without errors. I would like to ask you a question fellas…. How would you do for searching in android, all the files that in the device exist?? I have the problem that I don’t get a root path and i don’t know how to explore all the directories to find the mp3 files…. Any advice or idea??

 

 

=================================

=================================

=================================

 

 

 

 

출처: http://help.adobe.com/en_US/as3/dev/WS5b3ccc516d4fbf351e63e3d118666ade46-7fe4.html#WS2A7C0A31-A6A9-42d2-8772-79166A98A085

 

Adobe AIR 1.0 and later



A File object is a pointer to a file or directory in the file system.
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 class

You can use the File class for the following:
  • Getting the path to special directories, including the user directory, the user's documents directory, the directory from which the application was launched, and the application directory
  • Coping files and directories
  • Moving files and directories
  • Deleting files and directories (or moving them to the trash)
  • Listing files and directories contained in a directory
  • Creating temporary files and folders
Once a File object points to a file path, you can use it to read and write file data, using the FileStream class.
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 objects

Each 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:
  • File.applicationStorageDirectory—a storage directory unique to each installed AIR application. This directory is an appropriate place to store dynamic application assets and user preferences. Consider storing large amounts of data elsewhere.
  • On Android and iOS, the application storage directory is removed when the application is uninstalled or the user chooses to clear application data, but this is not the case on other platforms.
  • File.applicationDirectory—the directory where the application is installed (along with any installed assets). On some operating systems, the application is stored in a single package file rather than a physical directory. In this case, the contents may not be accessible using the native path. The application directory is read-only.
  • File.desktopDirectory—the user’s desktop directory. If a platform does not define a desktop directory, another location on the file system is used.
  • File.documentsDirectory—the user’s documents directory. If a platform does not define a documents directory, another location on the file system is used.
  • File.userDirectory—the user directory. If a platform does not define a user directory, another location on the file system is used.
Note: When a platform does not define standard locations for desktop, documents, or user directories, File.documentsDirectory, File.desktopDirectory, and File.userDirectory can reference the same directory.
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 directory

There are different ways to set a File object to point to a directory.

Pointing to the user’s home directory

You 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 directory

You 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 directory

You 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 directory

You 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:
  • On Mac OS — varies by AIR version:AIR 3.3 and laterpath/Library/Application Support/applicationID/Local Store, where path is either /Users/username/Library/Containers/bundle-id/Data (sandboxed environment) or /Users/username ( when running outside a sandboxed environment)
  • For example (AIR 3.2):
  • AIR 3.2 and earlier: /Users/user name/Library/Preferences/applicationID/Local Store/
  • On Windows—In the documents and Settings directory, in:For example:
  • C:\Documents and Settings\user name\Application Data\applicationID\Local Store\
  • On Linux—In:For example:
  • /home/user name/.appdata/applicationID/Local Store/
  • On Android—In:For example:
  • /data/data/androidPackageID/applicationID/Local Store
Note: If an application has a publisher ID, then the publisher ID is also used as part of the path to the application storage 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 directory

You 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 directory

You 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 root

The 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 directory

You 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 paths

You 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 directory

The 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 invoked

You 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 file

There are different ways to set the file to which a File object points.

Pointing to an explicit file path

Important: 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 directory

You 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 file

The 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:
  • browseForOpen()
  • browseForSave()
  • browseForOpenMultiple()
These methods are each asynchronous. The browseForOpen() and browseForSave() methods dispatch the select event when the user selects a file (or a target path, in the case of browseForSave()). With the browseForOpen() and browseForSave() methods, upon selection the target File object points to the selected files. The browseForOpenMultiple() method dispatches a selectMultiple event when the user selects files. The selectMultiple event is of type FileListEvent, which has a files property that is an array of File objects (pointing to the selected files).
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 paths

You 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 schemes

In AIR, you can use any of the following URL schemes in defining the url property of a File object:


Controlling file backup and caching

Certain 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.
  • To specify that a file does not need to be backed up and (iOS only) can be deleted by the operating system if device storage space runs low, save the file in the cache directory (File.cacheDirectory). This is the preferred storage location on iOS and should be used for most files that can be regenerated or re-downloaded.
  • To specify that a file does not need to be backed up, but should not be deleted by the operating system, save the file in one of the application library directories such as the application storage directory (File.applicationStorageDirectory) or the documents directory (File.documentsDirectory). Set the File object’s preventBackup property to true. This is required by Apple for content that can be regenerated or downloaded again, but which is required for proper functioning of your application during offline use.
Specifying files for backup
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 files

You 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 names

File 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 links

Various 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 volume

The 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 application

In 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.

 

 

 

 

 

 

=================================

=================================

=================================

 

 

 

 

출처: http://stackoverflow.com/questions/8119681/saving-reading-a-file-from-file-applicationstoragedirectory-in-an-ipad-flex4-5-a

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();
}

 

 

=================================

=================================

=================================

 

 

 

 

 

반응형


관련글 더보기

댓글 영역