?在flex中显示服务器端的图片可以使用Image控件的source属性,但是这个条件必须是客户端可以访问到的有效的URL地址。如果图片存储在数据库中,直接使用source属性是无法显示图片的。这种情况下可以使用flex中的URLStream类来读取文件流,然后把文件显示到画面上。
第一步,创建一个URLStream对象,然后调用这个对象的load函数从服务器端读取图片文件的内容。
view plain
copy to clipboard
print
?
- private?var?stream:URLStream?=?new?URLStream();??
-
private?function?onShow():void??
- {??
-
????var?downLoadURL:URLRequest?=?new?URLRequest();??
-
????downLoadURL.url?=?"http://localhost:8080/LoadPicture/download";??
- ????stream.addEventListener(Event.COMPLETE,?onLoadComplete);??
- ????stream.load(downLoadURL);??
- }??
第二步,把文件的内容保存到ByteArray中。在第一步中,为URLStream对象的COMPLETE事件注册了监听函数onLoadComplete,在这个函数中把得到的文件内容把文件的内容保存到ByteArray中。
view plain
copy to clipboard
print
?
-
private?var?stream:URLStream?=?new?URLStream();??
-
private?function?onLoadComplete(event:Event):void??
-
{??
-
????if?(stream.connected)??
-
????{??
-
????????var?b:int;??
-
????????try?{??
-
????????????do?{??
-
????????????????b?=?stream.readByte();??
-
????????????????bytes.writeByte(b);??
-
????????????}?while?(true);??
-
????????}?catch?(e:EOFError)?{??
-
????????????Alert.show(bytes.length.toString());??
-
????????}??
-
????}??
-
????var?bmp:Loader?=?new?Loader();??
-
????bmp.loadBytes(bytes);??
-
????pic.addChild(bmp);??
- }??
在取文件内容的时候,可以一个字节一个字节的取,当去到文件流的末尾时会抛出EOFError。
第三步,取到了文件内容之后就是把图片显示到画面上了,这里需要用到Loader类。使用Loader类的loadBytes函数,把图片内容放到Loader对象中,然后把Loader对象加到Image控件中就可以了。
服务器端的工作:
服务器端必须把图片文件准备还,然后在客户端请求数据的时候把文件流输出到客户端就可以了。
下面的例子是个java实现的。
view plain
copy to clipboard
print
?
-
private?void?downLoad(HttpServletResponse?response)?throws?Exception?{??
-
??
-
????BufferedOutputStream?bos?=?null;??
-
????BufferedInputStream??bis?=?null;??
-
????try?{??
-
????????bis?=?new?BufferedInputStream(new?FileInputStream("c:/head.PNG"));????????????
-
????????bos?=?new?BufferedOutputStream(response.getOutputStream());??
-
??????????
-
????????byte[]?buff?=?new?byte[2048];??
-
????????int?bytesRead;??
-
??
-
????????while(-1?!=?(bytesRead?=?bis.read(buff,?0,?buff.length)))?{??
-
????????bos.write(buff,0,bytesRead);??
-
????????}??
-
????}?catch(final?IOException?e)?{??
-
????????e.printStackTrace();??
-
????}?catch(Exception?e)?{??
-
????????e.printStackTrace();??
-
????}finally?{??
-
????????if?(bis?!=?null)??
-
????????bis.close();??
-
????????if?(bos?!=?null)??
-
????????{??
-
????????bos.flush();??
-
????????bos.close();??
-
????????bos=null;??
-
????????}??
-
????}??
-
????response.flushBuffer();??
- }??
?
完整例子下载地址:
http://download.csdn.net/source/1815371
?
提示:使用本例的时候需要在c:/放置一个文件名为“head.PNG”的图片。