I am using the code from this post link here to download remote SWF files to disk.
I have an XML file that lists 3 SWF files and I am using a for each loop to go through them. Tracing out the names, shows all 3 unique file names.
When using the file download code inside the for each loop, only the last file from the list is being saved.
My exact code:
function onPlaylistComplete(e:Event)
{
var List:XML = new XML(e.target.data);
trace("List : " + List);
for each(var item in List.playlist_ads.ad.ad_file_path)
{
var urlString:String = site_url + "/" + item;
var urlReq:URLRequest = new URLRequest(urlString);
var urlStream:URLStream = new URLStream();
urlStream.addEventListener(Event.COMPLETE, loaded);
urlStream.load(urlReq);
function loaded(event:Event):void
{
var fileData:ByteArray = new ByteArray();
urlStream.readBytes(fileData, 0, urlStream.bytesAvailable);
writeBinaryFile(item, fileData);
}
}
}
function writeBinaryFile(name : String, array : ByteArray) : void {
try {
var f : File = File.documentsDirectory.resolvePath(name);
var fs : FileStream = new FileStream();
fs.open(f, FileMode.WRITE);
fs.writeBytes(array);
fs.close();
trace(f.nativePath + " written.");
}
catch (err : Error) {
trace(err.name);
}
}
I'm thinking that somehow the bytearray isn't being cleared out, or i need to use a bytearray per file?
Hope you can help.
UPDATE - I tried the following code, taking the completion event handler out of the loop, still having the same problem and the last filename is being used. been stuck trying all manner of things for the past few hours!
for(i = 0; i < adArray.length; i++)
{
var swfItem = adArray[i];
var urlString:String = site_url + "/" + adArray[i];
var urlReq:URLRequest = new URLRequest(urlString);
var urlStream:URLStream = new URLStream();
urlStream.addEventListener(Event.COMPLETE, urlStreamComplete);
urlStream.load(urlReq);
}
function urlStreamComplete(event:Event):void
{
var fileData:ByteArray = new ByteArray();
var stream = event.target;
stream.readBytes(fileData, 0, stream.bytesAvailable);
try {
var f : File = File.documentsDirectory.resolvePath(swfItem);
var fs : FileStream = new FileStream();
fs.open(f, FileMode.WRITE);
fs.writeBytes(fileData);
fs.close();
trace(f.nativePath + " written.");
}
catch (err : Error) {
trace(err.message);
}
}