Problems loading XML file (url cannot load) on local machine - actionscript-3

I'm trying to have my flash application interpret an XML file. My code looks like:
function onFinish(success_boolean, results_obj, xml)
{
if (success_boolean)
{
play ();
} // end if
} // End of the function
Stage.align = "MC";
Stage.scaleMode = "noScale";
url = "25358";
_root.cacheKiller = "true";
stop ();
var parsed_obj = {};
var unCash = new Date().getTime();
if (_root.cacheKiller == "true")
{
fileToLoad = url + "_main.xml?cacheKiller=" + unCash;
fileToLoad = url + "_main.xml";
}
else
{
fileToLoad = url + "_main.xml";
} // end else if
gs.dataTransfer.XMLParser.load(fileToLoad, onFinish, parsed_obj);
_root.emp.useHandCursor = 0;
_root.mus = 1;
_root.n = 1;
_root.num = 1;
the output i get is:
Error opening URL 'file:///C|/try/25358undefined'
Does anyone have any idea why i can't access this file? I've verified that the URL works.

You have a wrong url. I mean that fileToLoad contains a wrong value. Try to trace this variable.

Related

script to read/write a file that is stored in a local "dropbox" folder or a local "google drive"

For the moment, the dropbox API allows a browser to access (read/write) all type of files in a dropbox folder on your local drive by script. The file path and name can be specified in the script. The script works on webpages that are stored on a local drive, but also works on webpages that are stored on a remote site when using Chrome.
Please see these jsfiddles with a primitive implementation to test writing and reading a text file in a local dropbox folder. The scripts are written in pure vanilla javascript code, and no not need a library.
Only a one-time access token is needed and no further authentication procedure.
This jsfiddle (click) demonstrates: Write text file to local dropbox folder
function WriteFile() {
var H = new Array(6);
H[0] = "Authorization";
H[1] = document.getElementById("bear").value;
H[2] = "Content-type";
H[3] = "application/octet-stream";
H[4] = "Dropbox-API-Arg";
H[5] = '{"path": "/' + document.getElementById("pana").value;
H[5] = H[5] + '","mode":{".tag":"overwrite"}}';
var X = new XMLHttpRequest();
X.onreadystatechange = acb;
X.open("POST", "https://content.dropboxapi.com/2/files/upload", true);
X.setRequestHeader(H[0], H[1]);
X.setRequestHeader(H[2], H[3]);
X.setRequestHeader(H[4], H[5]);
X.send(document.getElementById("myText").value);
document.getElementById("demo").innerHTML = "writing . . .";
}
function acb(A) {
var X = A.target;
var G = X.readyState;
if (G != 4) {
return 0;
}
document.getElementById("demo").innerHTML = "status: " + X.status;
}
This jsfiddle (click) demonstrates: Read text file from local dropbox folder
function ReadFile() {
document.getElementById("text").value = "";
var H = new Array(6);
H[0] = "User-Agent";
H[1] = "api-explorer-client";
H[2] = "Authorization";
H[3] = document.getElementById("bear").value;
H[4] = "Content-type";
H[5] = "application/json";
var X = new XMLHttpRequest();
X.onreadystatechange = acb;
X.open("POST", "https://api.dropboxapi.com/2/sharing/create_shared_link", true);
X.setRequestHeader(H[0], H[1]);
X.setRequestHeader(H[2], H[3]);
X.setRequestHeader(H[4], H[5]);
X.send('{"path": "/' + document.getElementById("pana").value + '"}');
document.getElementById("stat").innerHTML = "Reading . . .";
}
// async call back 1
function acb(A) {
var X = A.target;
if (X.readyState != 4) {
return 0; // when ready
}
var stat = X.status;
document.getElementById("stat").innerHTML = "status: " + stat;
if (stat != 200) {
document.getElementById("text").value = "NOT FOUND";
return 0; // error
}
var B = X.responseText;
var C = JSON.parse(B);
var D = C.url;
var E = D.split(".com");
var F = E[1];
var G = "https://dl.dropboxusercontent.com" + F;
document.getElementById("text").value = G;
X = new XMLHttpRequest();
X.onreadystatechange = acb2;
X.open("GET", G, true);
X.send(null);
}
// async callback 2
function acb2(A) {
var X = A.target;
if (X.readyState != 4) {
return 0; // when ready
}
var stat = X.status;
if (stat != 200) {
document.getElementById("text").value = "Can't Read the file";
return 0; // error
}
var B = X.responseText;
document.getElementById("text").value = B;
}
I tried to obtain the same functionality for files in a "google drive" on a local drive , using the "google drive API", but without success. Can someone achieve this, eventually using other cloud storage systems.

loading files to externally hosted swf actionscript 3

I have created a music playing flash, it works great and all when I'm running it from my local storage i.e (opening the swf directly from my computer)
but when I open the swf from a server it doesn't load the file. I've added the input handler below.
function addTrack(){
var trackChecker: URLLoader = new URLLoader();
if (String(path.text).substr(-4, 4) == ".mp3") {
txtError.text = "";
trackChecker.load(new URLRequest(String(path.text)))
} else {
if (String(path.text).substr(-4, 1) == ".") {
txtError.text = "Wrong format, tried to open " + String(path.text).substr(-4, 4) + ", but the only currently supported format is .mp3";
} else {
path.appendText(".mp3");
txtError.text = "";
trackChecker.load(new URLRequest(String(path.text)))
}
}
trackChecker.addEventListener(Event.COMPLETE, addToList);
trackChecker.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
}
function onIOError(e: IOErrorEvent) {
txtError.text = "No file found or file is damaged";
}
function addToList(e: Event) {
addedTrack = true;
tempSong = new Sound();
tempSong.load(new URLRequest(String(path.text)));
tempSong.addEventListener(Event.COMPLETE, tempData);
ActualArray[ActualArray.length] = ["Placeholder", "Placeholder", "Placeholder", "Placeholder", String(path.text)];
}
function tempData(e: Event) {
var tempTrackName;
var tempName: Array = tempSong.url.split("/");
if (String(tempSong.id3.songName) == "null") {
tempTrackName = String(tempName[tempName.length - 1].replace(".mp3", ""));
} else {
tempTrackName = (String(tempSong.id3.songName));
}
path.text = "";
for (var i: int = 3; i < tA.length - 1; i++) {
path.appendText(tempName[i]);
path.appendText("\\");
}
addToGrid(int(ActualArray.length - 1), tempSong.length, tempTrackName);
path.setSelection(path.text.length, path.text.length);
}
Worth noting that the script stops before it can change path.text, i.e. in the middle of "function tempData(e: Event)" or earlier. in stop i mean nothing happens, the other scripts work, but when you try to add a track nothing happens at all. but I can't recreate the glitch on my computer, because it only exists when the swf is hosted externally.

How to get byteArray or base64 string from RenderTexture Cocos2d-JS

I am making a game on cocos2d-JS for facebook in which there is a requirement of sharing a screenshot of the game.
I am able to take the screenshot but now I am unable to upload it in the Parse.com server because it requires base64 format or byte array. I am unable to find any solution of converting Sprite in to this format.. Here's my code so result when I do addchild its coming proper .. I have also added my commented code so that it will help to understand that I have tried lot of things but couldnt achieve the same.
shareToSocialNetworking: function () {
cc.director.setNextDeltaTimeZero(true);
var newsize = cc.director.getVisibleSize();
var renderText = new cc.RenderTexture(newsize.width,newsize.height);
renderText.begin();
cc.director.getRunningScene().visit();
renderText.end();
var result = cc.Sprite.create(renderText.getSprite().getTexture());
result.flippedY = true;
this._mainViewNode.addChild(result,6000);
//renderText.saveToFile("screenshot.jpg",cc.IMAGE_FORMAT_PNG);
//var based = renderText.getSprite().getTexture().getStringForFormat().toString();
//var data = based.getData();
var file = new Parse.File("screen.jpg", { base64: this.getBase64(result) });
//var file = new Parse.File("screen.jpg", data, "image/png");
var self = this;
file.save().then(function() {
// The file has been saved to Parse.
alert(file.url);
this.onSharePictureInfoLink(file.url());
}, function(error) {
// The file either could not be read, or could not be saved to Parse.
});
//
//var ccImage = renderText.newCCImage();
//
//var str = ccImage.getData();
},
is there any workaround that can be done
there is a private variable called _cacheCanvas, which is the instance of the offscreen canvas
you can simply do renderText._cacheCanvas.toDataURL()
Here's how you can take the screnshot from cocos2d-JS
screenshot: function (fileName) {
var tex = new cc.RenderTexture(winSize.width, winSize.height, cc.Texture2D.PIXEL_FORMAT_RGBA8888);
tex.setPosition(cc.p(winSize.width / 2, winSize.height / 2));
tex.begin();
cc.director.getRunningScene().visit();
tex.end();
var imgPath = jsb.fileUtils.getWritablePath();
if (imgPath.length == 0) {
return;
}
var result = tex.saveToFile(fileName, cc.IMAGE_FORMAT_JPEG);
if (result) {
imgPath += fileName;
cc.log("save image:" + imgPath);
return imgPath;
}
return "";
}
then make a Java call from Javascript
public static void ScreenShot()
{
Bitmap imageBitmap = BitmapFactory.decodeFile(Cocos2dxHelper.getCocos2dxWritablePath() + "/" + "screenshot.png");
String fileHolder = "SampleFolder";
File filepathData = new File("/sdcard/" + fileHolder);
//~~~Create Dir
try {
if (!filepathData.exists())
{
filepathData.mkdirs();
filepathData.createNewFile();
FileWriter fw = new FileWriter(filepathData + fileHolder);
BufferedWriter out = new BufferedWriter(fw);
String toSave = String.valueOf(0);
out.write(toSave);
out.close();
}
}
catch (IOException e1) {
}
//~~~Create Image
File file = new File("/sdcard/" + "Your filename");
try
{
file.createNewFile();
FileOutputStream ostream = new FileOutputStream(file);
imageBitmap.compress(CompressFormat.PNG, 100, ostream);
ostream.close();
}
catch (Exception e) {}
Uri phototUri = Uri.fromFile(file);
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, phototUri);
//~~~Add Code Below
}
Do not forget to add permission for external storage

Parse URL (ActionScript 3.0)

I would like to know how would one parse an URL.
protocol://mydomain.com/something/morethings/this_is_what_i_want/even_if_it_has_slashes
I need to get "this_is_what_i_want/even_if_it_has_slashes"
How should I do this?
Thanks!
Try this :
var u:String = 'protocol://mydomain.com/something/morethings/this_is_what_i_want/even_if_it_has_slashes',
a:Array = u.split('/'),
s:String = ''
for(var i=0; i<a.length; i++){
if(i > 3){
s += '/'+a[i]
}
}
trace(s) // gives : /morethings/this_is_what_i_want/even_if_it_has_slashes
Another approach would be using Regex like this:
.*?mydomain\.com[^\/]*\/[^\/]+\/[^\/]+\/([^?]*)
(Breakdown of the components.)
This looks for a pattern where it skips whatever comes before the domain name (doesn't matter if the protocol is specified or not), skips the domain name + TLD, skips any port number, and skips the first two sub path elements. It then selects whatever comes after it but skips any query strings.
Example: http://regexr.com/39r69
In your code, you could use it like this:
var url:String = "protocol://mydomain.com/something/morethings/this_is_what_i_want/even_if_it_has_slashes";
var urlExp:RegExp = /.*?mydomain\.com[^\/]*\/[^\/]+\/[^\/]+\/([^?]*)/g;
var urlPart:Array = urlExp.exec(url);
if (urlPart.length > 1) {
trace(urlPart[1]);
// Prints "this_is_what_i_want/even_if_it_has_slashes"
} else {
// No matching part of the url found
}
As you can see on the regexr link above, this captures the part "this_is_what_i_want/even_if_it_has_slashes" for all of these variations of the url:
protocol://mydomain.com/something/morethings/this_is_what_i_want/even_if_it_has_slashes
protocol://mydomain.com:8080/something/morethings/this_is_what_i_want/even_if_it_has_slashes
protocol://mydomain.com/something/morethings/this_is_what_i_want/even_if_it_has_slashes.html
protocol://mydomain.com/something/morethings/this_is_what_i_want/even_if_it_has_slashes.html?hello=world
mydomain.com/something/morethings/this_is_what_i_want/even_if_it_has_slashes
protocol://subdomain.mydomain.com:8080/something/morethings/this_is_what_i_want/even_if_it_has_slashes
Edit: Fixed typo in regexp string
Simple way,
var file:String = 'protocol://mydomain.com/something/morethings/this_is_what_i_want/even_if_it_has_slashes';
var splitted:Array = file.split('/');
var str1:String = splitted.splice(3).join('/'); //returns 'something/morethings/this_is_what_i_want/even_if_it_has_slashes'
var str1:String = splitted.splice(5).join('/'); //returns 'this_is_what_i_want/even_if_it_has_slashes'
If you want to be a little more flexible in the feature (e.g. you need the domain), you can use my Url class.
Class for URL parsing
package
{
import flash.net.URLVariables;
public class Url
{
protected var protocol:String = "";
protected var domain:String = "";
protected var port:int = 0;
protected var path:String = "";
protected var parameters:URLVariables;
protected var bookmark:String = "";
public function Url(url:String)
{
this.init(url);
}
protected function splitSingle(value:String, c:String):Object
{
var temp:Object = {first: value, second: ""};
var pos:int = value.indexOf(c);
if (pos > 0)
{
temp.first = value.substring(0, pos);
temp.second = value.substring(pos + 1);
}
return temp;
}
protected function rtrim(value:String, c:String):String
{
while (value.substr(-1, 1) == c)
{
value = value.substr(0, -1);
}
return value;
}
protected function init(url:String):void
{
var o:Object;
var urlExp:RegExp = /([a-z]+):\/\/(.+)/
var urlPart:Array = urlExp.exec(url);
var temp:Array;
var rest:String;
if (urlPart.length <= 1)
{
throw new Error("invalid url");
}
this.protocol = urlPart[1];
rest = urlPart[2];
o = this.splitSingle(rest, "#");
this.bookmark = o.second;
rest = o.first;
o = this.splitSingle(rest, "?");
o.second = this.rtrim(o.second, "&");
this.parameters = new URLVariables();
if (o.second != "")
{
try
{
this.parameters.decode(o.second);
}
catch (e:Error)
{
trace("Warning: cannot decode URL parameters. " + e.message + " " + o.second);
}
}
rest = o.first
o = this.splitSingle(rest, "/");
if (o.second != "")
{
this.path = "/" + o.second;
}
rest = o.first;
o = this.splitSingle(rest, ":");
if (o.second != "")
{
this.port = parseInt(o.second);
}
else
{
switch (this.protocol)
{
case "https":
this.port = 443;
break;
case "http":
this.port = 80;
break;
case "ssh":
this.port = 22;
break;
case "ftp":
this.port = 21;
break;
default:
this.port = 0;
}
}
this.domain = o.first;
}
public function getDomain():String
{
return this.domain;
}
public function getProtocol():String
{
return this.protocol;
}
public function getPath():String
{
return this.path;
}
public function getPort():int
{
return this.port;
}
public function getBookmark():String
{
return this.bookmark;
}
public function getParameters():URLVariables
{
return this.parameters;
}
}
}
Example usage
try {
var myUrl:Url = new Url("protocol://mydomain.com/something/morethings/this_is_what_i_want/even_if_it_has_slashes");
trace("Protocol: " + myUrl.getProtocol());
trace("Domain: " + myUrl.getDomain());
trace("Path: " + myUrl.getPath());
trace("What you want: " + myUrl.getPath().split("/").splice(2).join("/") );
} catch (e:Error) {
trace("Warning: cannot parse url");
}
Output
Protocol: protocol
Domain: mydomain.com
Path: /something/morethings/this_is_what_i_want/even_if_it_has_slashes
What you want: morethings/this_is_what_i_want/even_if_it_has_slashes
Description
The init function checks with the regular expression if the given url starts with some letters (the protocol) followed by a colon, two slashes and more characters.
If the url contains a hash letter, everything behind its fist occurrence is taken as a bookmark
If the url contains a question mark, everything behind its fist occurrence is taken as key=value variables and parsed by the URLVariables class.
If the url contains a slash, everything behind its first occurrence is taken as the path
If the rest (everything between the last protocol slash and the first slash of the path) contains a colon, everything behind it will be converted to an integer and taken as the port. If the port is not set, a default will be set in dependency of the protocol
The rest is the domain
For answering your question, I use the path of the given url, split it by slash, cut of the 'something' and join it by slash.

Upload pre-selected file with actionscript

I'm creating a photoshop extension where I need to save the file people are working on and upload it to a server. So I want the extension to be able to automatically choose the current file and upload it to my server.
Problem is I don't know how to pre-select a file for people. Here's my code so far:
var app:Application = Photoshop.app;
var doc:Document = app.documents.add();
doc.selection.selectAll();
var color:RGBColor = new RGBColor();
color.red = 0;
color.green = 0;
color.blue = 255;
doc.selection.fill(color);
var saveOptions:JPEGSaveOptions = new JPEGSaveOptions();
//Add other PDF save options here.
doc.saveAs(File.applicationStorageDirectory, saveOptions);
var jsonOBJ:Object = {};
jsonOBJ.option = "iphone";
jsonOBJ.title = "c";
jsonOBJ.description = "s";
jsonOBJ.app_store_url = "iphone";
jsonOBJ.tags = "c";
jsonOBJ.temp_number = 1;
var _service:HTTPService = new HTTPService();
_service.url = "http://localhost:3000/designs";
_service.method = "POST";
_service.contentType = "application/json";
_service.resultFormat = "text";
_service.useProxy = false;
_service.makeObjectsBindable = true;
_service.addEventListener(FaultEvent.FAULT,faultRX);
_service.addEventListener(ResultEvent.RESULT,resultRX);
_service.showBusyCursor = true;
_service.send( JSON.encode( jsonOBJ ) );
function resultRX():void
{
trace(ResultEvent.RESULT);
}
function faultRX():void
{
trace(FaultEvent.FAULT);
}
var file:FileReference;
var filefilters:Array;
var req:URLRequest;
filefilters = [ new FileFilter('Images', '*.jpg') ]; // add other file filters
file.browse(filefilters);
It's a photoshop extension. I ended up using FileReference and link to the file. it worked. I dunno how to actually upload the image though. When I use file.upload(requestUrl), it sends along a wrong content type. –