How to put\save files into your application directory? (adobe air) - actionscript-3

How to put\save files into your application directory? (adobe air) (code example, please)

It's not recomended but it is possible. Construct your File reference like this:
var pathToFile:String = File.applicationDirectory.resolvePath('file.txt').nativePath;
var someFile:File = new File(pathToFile);

You can't write to your AIR app's Application Directory, it's not allowed. You can however write to a folder that your AIR app creates in the user's directory, called the Application Storage Directory. If you need config files and the like, that's probably the best place to put them. See 'applicationDirectory' in the docs link below:
http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/

#glendon
if you try to save directly to applicationDirectory it will indeed throw an error, but it seems you can move the file in the filesystem. i used the code below after yours:
var sourceFile:File = File.applicationStorageDirectory.resolvePath ("file.txt");
var pathToFile:String = File.applicationDirectory.resolvePath ('file.txt').nativePath;
var destination:File = new File (pathToFile);
sourceFile.moveTo (destination, true);
the reason why you 'shouldnt' use the application folder is because not all users have rights to save files in such folder, while everyone will in applicationStorageDirectory.

The accepted answer works!
But if I do this instead:
var vFile = File.applicationDirectory.resolvePath('file.txt');
var vStream = new FileStream();
vStream.open(vFile, FileMode.WRITE);
vStream.writeUTFBytes("Hello World");
vStream.close();
It will give SecurityError: fileWriteResource. However, if I use applicationStorageDirectory instead, the above code will work. It'll only NOT work if it's applicationDirectory. Moreover, Adobe's documentation also says that an AIR app cannot write to its applicationDirectory.
Now, I wonder if it's a bug on Adobe's part that they allow writing to the applicationDirectory using the way suggested by the accepted answer.

try this.
var objFile:File = new File(“file:///”+File.applicationDirectory.resolvePath(strFilePath).nativePath);
the output would be like this…
file:///c:\del\userConf.xml
This will work fine.

If you want write file into ApplicationDirectory, right?
Please don't forget for write for nativeprocess via powershell with registry key for your currect adobe application ( example: C:\Program Files (x86)\AirApp\AirApp.exe with RunAsAdmin )
nativeprocess saves new registry file
AirApp will restarts into RunASAdmin
AirApp can be writable possible with file :)
Don't worry!
I know that trick like sometimes application write frist via registry file and calls powershell by writing nativeprocess into registry file into registry structures.
Look like my suggestion from adobe system boards / forum was better than access problem with writing stream with file :)
I hope you because you know my nice trick with nativeprocess via powershell + regedit /s \AirApp.reg
and AirApp changes into administratived AirApp than it works fine with Administratived mode :)
Than your solution should write and you try - Make sure for your writing process by AirApp.

this function gives your current air application folder which bypasses the security problem:
function SWFName(): String {
var swfName: String;
var mySWF = new File(this.loaderInfo.url).nativePath;
swfName= this.loaderInfo.loaderURL;
swfName = swfName.slice(swfName.lastIndexOf("/") + 1); // Extract the filename from the url
swfName = new URLVariables("path=" + swfName).path; // this is a hack to decode URL-encoded values
mySWF = mySWF.replace(swfName, "");
return mySWF;
}

Related

I Want To add FileFilter ("*.doc") to save automatic file without type extension

I want to add my FileFilter in as3. Because there is the main problem of extension typing. I already use this option
(saveFile.save(bytes,_dbookNameFill+".doc"));
but I want to automatically generate this extension when I save my file any names. Please Help Me I am Mini Programmer.
var bytes:ByteArray = document.save(Method.LOCAL);
var saveFile:FileReference = new FileReference()
var _dbookNameFill:String =
QSTPreviwForStudentMC._bookNameMc.bookNtxt.text;
var fileFilter:FileFilter=new FileFilter("*.doc","*.text;*.RTF;");
saveFile.save(bytes,_dbookNameFill+".doc");
I'm afraid this won't work. Using AS3's FileFilter class you're just able to limit
what's being displayed on a file dialog you've opened using Filereference.browse().
FileReference.save() isn't affected by a FileFilter and as far as I know there is
no way to force a particular file extension - perhaps due to security reasons.

Read user directory in HTML 5 and load images in it

I've been toying around with the FileSystem and File API, in Chrome, to try to implement a transient "instant gallery". The user chooses a directory, and all the images in it are then displayed in the webpage.
But I'm having a hard time, it seems Chrome requires some extra launching arguments to allow file access, FileSystem and File API are not W3C and not portable, I cannot instantiate certain objects...
I cannot even get the directory absolute path to open files in it (though maybe I don't need the absolute path, but I feel like it lacks a good documentation).
Anyway, I wanted to know how to implement this? Is there another API? A simpler way? Do I absolutely need to use FileSystem and File, and set Chrome's arguments?
In order to read the files in the directory you will need to create a DirectoryReader object, and use the readEntries() method to read the content of the directory:
fs.root.getDirectory('Documents', {}, function(dirEntry){<br>
var dirReader = dirEntry.createReader();
dirReader.readEntries(function(entries) {<br>
for(var i = 0; i < entries.length; i++) {
var entry = entries[i];
if (entry.isDirectory){
console.log('Directory: ' + entry.fullPath);
}
else if (entry.isFile){
console.log('File: ' + entry.fullPath);
}
}
}, errorHandler);
}, errorHandler);
Please take a look here: http://code.tutsplus.com/tutorials/toying-with-the-html5-filesystem-api--net-24719
But I think that Chrome will not be able to access an entire directory that the user has selected from his computer, only if the user has selected multiple files in an input field. If that is ok and suits your needs there is a good tutorial here:
http://www.html5rocks.com/en/tutorials/file/dndfiles/

Node settings file vs mysql store

i've build my first Node app in which i need to use 5-10 global variables a lot. The thing is i would like to be able to change those values without restarting the server.
So what i though was setup an interval and update those files either from a ( JSON ? ) file or through a couple of queries to the database.
Now what would be my better option here ? Both mysql and read file modules are used in the app.
Security based wouldn't it be best to place the json file behind the public folder and read from that ? Although without sql injection being possible i think in the DB should be pretty safe too.
What do you guys think ?? Still a newbie in Node JS.
Thanks
With yamljs, the overhead is that you will need to install it. From your question, it seems you are already using a bunch of 3rd party modules in your app.
Why not use something that is a part of node.js itself?
Use the fs module.
Example:
var fs = require('fs');
var obj;
fs.readFile('myData.json', 'utf8', function (err, data) {
if (err) throw err;
obj = JSON.parse(data);
});
Docs: https://nodejs.org/api/fs.html#fs_fs_readfile_file_options_callback
A common technique for passing configuration variables to a server is via a YAML file. Normally this file is read once when the server starts but you could periodically query they file to see when it was last updated and if the file was changed update the configuration variables currently in use.
yamljs
YAML = require('yamljs');
config = YAML.load('myfile.yml');
then you can periodically check the last time a file was modified using the mtime property of fs.stat
fs.stat(path, [callback])
If you find that the last modified time has changed then you can re-read the YAML file and update your config with the new values. ( you will probably want to do a sanity check to make sure the file wasn't corrupted etc. )
If you don't want to write the file watching logic yourself I recommend checking out chokidar
// Initialize watcher.
var watcher = chokidar.watch('myfile.yml', {
ignored: /[\/\\]\./,
persistent: true
});
// Add event listeners.
watcher.on('change', function(path) {
// Update config
})

Is it possible to retrieve xml from server, save to device and use that local file for my HTTPService url?

I have an app that retrieves XML From a server I run... Im trying to limit the calls to the server (if possible) to improve responsiveness of the app and decrease the likelihood that the user will get errors if the data stream doesnt make the trip successfully for whatever reason -- i get some intermittent network monitor errors, it could be due to some wifi channel conflicts I think I have, but its still is a potential weak point in the overall process and if I can work around that need to call to the server each time the user performs an 'action' within the app.
what I'd like to do is use the local storage on the device to (upon launch of the app) retrieve and save the XML data, then change my httpservice url the local file.
I have some code I used before to successfully write and read config settings to a local text file, so Im pretty sure this can be achieved, just not sure how exactly to go about it.
thanks for any light someone can shed on this or any code examples anyone can share.
Load it by default from the applicationStorageDirectory if it doesnt exist donwload and save the xml to the applicationStorageDirectory
to load:
var xmlFile:File = File.applicationStorageDirectory.resolvePath("data.xml");
if (xmlFile.exists)
{
var fileStream:FileStream = new FileStream();
fileStream.open(xmlFile, FileMode.READ);
var xml:XML = XML(fileStream.readUTFBytes(fileStream.bytesAvailable));// you will want to declare outside this scope, its just for show
fileStream.close();
}else{
downloadAndSaveXML();// if it doesnt exist dowload it then save it and call load again!
}
to save:
//download .xml first and save in the onComplete handler, im calling the file "xml"
var file:File = File.applicationStorageDirectory.nativePath("data.xml");
var stream:FileStream = new FileStream();
stream.open(file, FileMode.WRITE);
stream.writeUTFBytes(xml.toXMLString());
stream.close();
get the idea?
You will also need this compiler argument so the HTTPService doesnt look online for the xml
-locale en_US -use-network=false
You could not bother with dowloading the file in the firstplace and just embed it in the Application
here a link to the topic

Actionscript 3.0 - incrementing a text file

I am looking for a quick and easy way to store variables in a text file, rather than use amfphp to connect to a database all I need to do is increment values every time a button is clicked .
Would be better if all the vars were in the same text file but if I have to have one per var that would be ok.
If your app is a desktop one, you can user AIR's File and FileStream classes in APPEND mode, like this:
// create the file reference
var file:File = File.documentsDirectory;
file = file.resolvePath("air_tests/saved_by_AIR.txt");
// create a stream object to read/write, and open in in APPEND mode
var stream:FileStream = new FileStream();
stream.open(file, FileMode.APPEND);
// add a new line to the text file
stream.writeUTFBytes( (new Date()).toString() + "\n" );
Desktop apps can use AIR's File and FileStream classes.
See protozoo's example for that.
However, if encryption is necessary, use the EncryptedLocalStore class.
var myVar:int=100; //This is what you'll increemnt.
var bytesToWrite:ByteArray=new ByteArray();
bytesToWrite.writeInt(myVar);
EncryptedLocalStore.setItem("myVar", bytesToWrite);
To retreive the value,
var storedValue:ByteArray = EncryptedLocalStore.getItem("myVar");
var readVar:int=storedValue.readInt();
You won't be able to save a file without a file dialog popping up (perhaps in AIR, but I haven't tested it), so this can quickly get annoying. If it's only for internal use - as in you don't need to access it outside of flash - then check out the SharedObject class instead: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/SharedObject.html
Works pretty much like a normal Object, it's just persisted over multiple plays