Skip to content

Instantly share code, notes, and snippets.

@lazuee
Created August 1, 2024 11:11
Show Gist options
  • Save lazuee/be5122e4bd2e55e5bee9cd63c0b05657 to your computer and use it in GitHub Desktop.
Save lazuee/be5122e4bd2e55e5bee9cd63c0b05657 to your computer and use it in GitHub Desktop.
Actionscript 3 - Downloader
package {
import flash.events.*;
import flash.net.*;
import flash.utils.*;
import flash.filesystem.*;
import flash.display.MovieClip;
public class Downloader {
public static function download(url: String): void {
var urlRequest: URLRequest = new URLRequest(url);
var urlStream: URLStream = new URLStream();
urlStream.addEventListener(Event.COMPLETE, onComplete);
urlStream.addEventListener(IOErrorEvent.IO_ERROR, onError);
urlStream.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
urlStream.load(urlRequest);
function onComplete(event: Event): void {
var parts:Array = url.split("/");
var domain:String = parts[2];
var fileName:String = parts.pop().split("?")[0];
var path:String = "/swf/" + domain + "/" + parts.slice(3).join("/") + "/" + fileName;
var file:File = File.userDirectory.resolvePath(File.applicationDirectory.resolvePath("").nativePath + path);
var fileData:ByteArray = new ByteArray();
var fileStream: FileStream = new FileStream();
urlStream.readBytes(fileData, 0, urlStream.bytesAvailable);
var directory: File = file.parent;
if (!directory.exists) {
directory.createDirectory();
}
trace("[Downloader] Path: " + file.nativePath);
fileStream.open(file, FileMode.WRITE);
fileStream.writeBytes(fileData, 0, fileData.length);
fileStream.close();
removeListeners();
}
function onError(event: ErrorEvent): void {
trace("[Downloader] Error: " + event.text);
removeListeners();
}
function removeListeners(): void {
urlStream.removeEventListener(Event.COMPLETE, onComplete);
urlStream.removeEventListener(IOErrorEvent.IO_ERROR, onError);
urlStream.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment