這些天正在研究flex圖片預覽上傳功能,因而找了一些資料進行了整理,造成了比較完整的示例,在此給本身留下參考資料。html
須要如下兩個jar包:commons-fileupload-1.2.jar和commons-io-1.4.jar服務器
上代碼,flex代碼dom
- <?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 p_w_picpathTypes:FileFilter=new FileFilter("Images (*.jpg, *.jpeg, *.png)", "*.jpg;*.jpeg;*.png");
- var allTypes:Array=new Array(p_w_picpathTypes);
- 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:ide
- /**
- * 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 p_w_picpathName = 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;
- p_w_picpathName = DateUtil.getNowStrDate() + rannum
- + item.getName();
- BufferedInputStream in = new BufferedInputStream(item
- .getInputStream());
- BufferedOutputStream out = new BufferedOutputStream(
- new FileOutputStream(new File(tempDirPath + "\\"
- + p_w_picpathName)));
- Streams.copy(in, out, true);
- }
- }
- }
源碼見附件post
訪問路徑爲
http://localhost:8080/upload_1/upload/upload.htmlflex