DownloadableImage.as
package
{
import flash.events.ContextMenuEvent;
import flash.net.FileReference;
import flash.net.URLRequest;
import flash.ui.ContextMenu;
import flash.ui.ContextMenuItem;
import mx.controls.Image;
import mx.core.Application;
public class DownloadableImage extends Image
{
public function DownloadableImage()
{
super();
}
override protected function createChildren():void
{
super.createChildren();
addDownloadContextMenu();
}
private function addDownloadContextMenu():void
{
contextMenu = new ContextMenu();
var item:ContextMenuItem = new ContextMenuItem("save as");
contextMenu.customItems.push(item);
item.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, menuItemSelectHandler);
}
private var fr:FileReference = new FileReference();
private function menuItemSelectHandler(event:ContextMenuEvent):void
{
if(event.currentTarget.caption == "save as")
{
if(source is String)
{
if(String(source).indexOf("http") > -1)
{
fr.download(new URLRequest(String(source)));
}
else
{
var pattern:RegExp = /(?P<protocol>http|https):\/\/(?P<host>[^\/]+)/;
var matches:Array = String(Application.application.url).match(pattern);
if(matches && matches.length > 0)
fr.download(new URLRequest(matches.protocol + "://" + matches.host + "/" + String(source)));
}
}
}
}
}
}
DownloadableImageDemo.mxml
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:local="*">
<local:DownloadableImage source="DownloadableImageDemo-picture.jpg"/>
</mx:Application>
demo:
http://hydra1983.googlepages.com/DownloadableImageDemo.html