如何用BlazeDS更改图片
相信大家在实际应用中肯定会碰到这样的问题:如何动态更改网元图片或者Topo背景?本文用具体实例演示了如何从本地上传图片到服务器,并设置为Topo背景。
首先介绍一下本文用到的技术:
1. FileReference
FileReference用于从本地打开文件,而且需要添加编译选项:-target-player=10.0.0。关于FileReference的用法请参考官方文档
FileReference API:
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/FileReference.html
2. BlazeDS
本文用BlazeDS上传文件,后续文章也使用了BlazeDS。更多关于BlazeDS的信息请参考官方网站
BlazeDS:http://opensource.adobe.com/wiki/display/blazeds/BlazeDS
下面进入正题:
1. 选择图片,然后将图片显示出来
private function selectImage():void {
fileReference = new FileReference();
fileReference.addEventListener(Event.SELECT, function(e:Event):void {
fileReference.load();
});
fileReference.addEventListener(Event.COMPLETE, function(e:Event):void {
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, function(event:Event):void {
image.source = event.target.content;
uploadButton.enabled = true;
});
loader.loadBytes(fileReference.data);
});
fileReference.browse([new FileFilter("Image Files", "*.jpg;*.jpeg;*.gif;*.png;*.JPG;*.JPEG;*.GIF;*.PNG")]);
}
2. 上传图片,并且在上传结束后,设置成Topo背景
1 private function uploadImage():void {
2 RemoteObjectUtil.invoke("UploadImage", "uploadFile", handleUploadSuccess, fileReference.name, fileReference.data);
3 }
4
5 private function handleUploadSuccess(result:Object):void {
6 if(result as Boolean && callBackFunction != null){
7 callBackFunction(fileReference.name);
8 PopUpManager.removePopUp(this);
9 }else{
10 Alert.show("Upload Image failed.");
11 }
12 };
1 uploadImage.callBackFunction = function(name:String):void {
2 var style:IStyle;
3 if(network.currentSubNetwork == null){
4 style = box;
5 }else{
6 style = network.currentSubNetwork;
7 }
8 style.setStyle(Styles.BACKGROUND_TYPE, Consts.BACKGROUND_TYPE_IMAGE);
9 style.setStyle(Styles.BACKGROUND_IMAGE, name);
10 };
3. 调用后台方法的代码如下:
1 public static function invoke(destination:String, method:String, callBack:Function, ... parameters:Array):void {
2 var remoteObject:RemoteObject = new RemoteObject(destination);
3 remoteObject.addEventListener(FaultEvent.FAULT, function(e:FaultEvent):void {
4 Alert.show(e.toString());
5 });
6 remoteObject.addEventListener(ResultEvent.RESULT, function(e:ResultEvent):void {
7 if(callBack != null){
8 callBack(e.result);
9 }
10 });
11 remoteObject.getOperation(method).send.apply(null, parameters);
12 }
4. 后台保存图片的代码如下,将PATH更改为Web工程部署后的目录:
1 public class UploadImage {
2 private final static String PATH = "F:/ws/java/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/BlazedsDemo/";
3
4 public boolean uploadFile(String fileName, byte[] content) throws Exception {
5 if (content == null || content.length == 0
6 || fileName == null || fileName.length() == 0){
7 return false;
8 }
9 File file = new File(PATH + fileName);
10 FileOutputStream stream = new FileOutputStream(file);
11 stream.write(content);
12 stream.close();
13 return true;
14 }
15 }
如需源代码可留言