这些天正在研究flex图片预览上传功能,于是找了一些资料进行了整理,形成了比较完整的示例,在此给自己留下参考资料。
需要以下两个jar包:commons-fileupload-1.2.jar和commons-io-1.4.jar
上代码,flex代码
- <?xml version="1.0" encoding="utf-8"?>
- <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
- layout="absolute"
- xmlns="*"
- creationComplete="init();">
- <mx:Script>
- <![CDATA[
- import flash.events.*;
- import mx.controls.Alert;
- import mx.events.CloseEvent;
- import mx.managers.CursorManager;
- private var file:FileReference;
- private var byteArray:ByteArray;
- private var bitmapData:BitmapData;
- private var loader:Loader=new Loader();
- private function init():void
- {
- Security.allowDomain("*");
- file=new FileReference();
- file.addEventListener(Event.COMPLETE, fileReferenceCompleteHandler);
- file.addEventListener(Event.SELECT, fileReferenceSelectHandler);
- }
- //选择上传的图片
- private function choose():void
- {
- var imageTypes:FileFilter=new FileFilter("Images (*.jpg, *.jpeg, *.png)", "*.jpg;*.jpeg;*.png");
- var allTypes:Array=new Array(imageTypes);
- file.browse(allTypes);
- // file.browse();
- }
- private function toUpload():void
- {
- if (bitmapData == null)
- {
- Alert.show("请您先选择要上传的图片");
- }
- else
- {
- Alert.show("上传 " + file.name + " (共 " + Math.round(file.size) + " 字节)?", "确认上传", Alert.YES | Alert.NO, null, proceedWithUpload);
- }
- }
- //监听文件上传状态
- private function onProgress(e:ProgressEvent):void
- {
- lbProgress.text=" 已上传 " + e.bytesLoaded + " 字节,共 " + e.bytesTotal + " 字节";
- var proc:uint=e.bytesLoaded / e.bytesTotal * 100;
- bar.setProgress(proc, 100);
- bar.label="当前进度: " + " " + proc + "%";
- if (e.bytesLoaded == e.bytesTotal)
- {
- CursorManager.removeBusyCursor();
- }
- }
- //上传图片到服务器
- private function proceedWithUpload(e:CloseEvent):void
- {
- if (e.detail == Alert.YES)
- {
- //进度监听
- file.addEventListener(ProgressEvent.PROGRESS, onProgress);
- var request:URLRequest=new URLRequest("http://localhost:8080/upload_1/servlet/upload");
- //设置鼠标忙状态
- CursorManager.setBusyCursor();
- try
- {
- file.upload(request);
- Alert.show("恭喜你,上传成功");
- }
- catch (error:Error)
- {
- Alert.show("上传失败");
- trace("上传失败");
- }
-
- }
- }
- //上传完成调用
- private function completeHandle(event:Event):void
- {
- Alert.show("恭喜你,上传成功");
- }
- //载入本地图片
- private function fileReferenceCompleteHandler(e:Event):void
- {
- byteArray=file.data;
- loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loaderCompleteHandler);
- loader.loadBytes(byteArray);
- }
- //图片载入完成显示在预览框中
- private function loaderCompleteHandler(e:Event):void
- {
- var bitmap:Bitmap=Bitmap(loader.content);
- bitmapData=bitmap.bitmapData;
- img.source=bitmap;
- }
- //选择文件动作监听
- private function fileReferenceSelectHandler(e:Event):void
- {
- file.removeEventListener(ProgressEvent.PROGRESS, onProgress);
- file.load();
- }
- ]]>
- </mx:Script>
- <mx:Canvas width="100%" height="100%" x="10" y="10" fontSize="15">
- <mx:Panel width="469"
- height="392"
- verticalGap="0"
- horizontalAlign="left"
- verticalAlign="top"
- x="0"
- y="0"
- layout="absolute">
- <mx:Image id="img" width="400" height="300" x="36" y="44"/>
- </mx:Panel>
- <mx:Button label="选择文件" click="choose();" x="500" y="400"/>
- <mx:VBox id="shangchuan" width="100%" horizontalAlign="center" visible="true">
- <mx:Label id="lbProgress" text="上传"/>
- <mx:ProgressBar id="bar"
- labelPlacement="bottom"
- minimum="0"
- visible="true"
- maximum="100"
- label="当前进度: 0%"
- direction="right"
- mode="manual"
- width="200"/>
- <mx:Button label="上传文件" click="toUpload();"/>
- </mx:VBox>
- </mx:Canvas>
- </mx:Application>
后台servlet:
- /**
- * get及post提交方式
- *
- * @param request
- * @param response
- * @throws ServletException
- * @throws IOException
- */
- @SuppressWarnings({ "rawtypes", "unchecked" })
- public void doGetAndPost(HttpServletRequest request,
- HttpServletResponse response) throws ServletException, IOException {
- request.setCharacterEncoding("GBK");
- // 文件存放的目录
- //C:\\Documents and Settings\\jnzbht\\Workspaces\\MyEclipse 8.5\\upload\\WebRoot\\upload\\
- File tempDirPath = new File(request.getSession().getServletContext().getRealPath("/")+ "\\upload\\");
- if (!tempDirPath.exists()) {
- tempDirPath.mkdirs();
- }
-
- // 创建磁盘文件工厂
- DiskFileItemFactory fac = new DiskFileItemFactory();
-
- // 创建servlet文件上传组件
- ServletFileUpload upload = new ServletFileUpload(fac);
-
- //使用utf-8的编码格式处理数据
- upload.setHeaderEncoding("utf-8");
-
- // 文件列表
- List fileList = null;
-
- // 解析request从而得到前台传过来的文件
- try {
- fileList = upload.parseRequest(request);
- } catch (FileUploadException ex) {
- ex.printStackTrace();
- return;
- }
- // 保存后的文件名
- String imageName = null;
- // 便利从前台得到的文件列表
-
- Iterator<FileItem> it = fileList.iterator();
-
-
- while (it.hasNext()) {
-
- FileItem item = it.next();
- // 如果不是普通表单域,当做文件域来处理
- if (!item.isFormField()) {
- //生成四位随机数
- Random r = new Random();
- int rannum = (int) (r.nextDouble() * (9999 - 1000 + 1)) + 1000;
-
- imageName = DateUtil.getNowStrDate() + rannum
- + item.getName();
-
- BufferedInputStream in = new BufferedInputStream(item
- .getInputStream());
- BufferedOutputStream out = new BufferedOutputStream(
- new FileOutputStream(new File(tempDirPath + "\\"
- + imageName)));
- Streams.copy(in, out, true);
-
- }
- }
- }
源码见附件
访问路径为
http://localhost:8080/upload_1/upload/upload.html
本文出自 “GUI” 博客,请务必保留此出处http://xingfudehunpo.blog.51cto.com/1843260/1112981