Flex 批量上传

 

Flex批量上传通过Servlet  

2009-12-15 19:28:06|  分类: Flex&AIR |  标签:批量上传  flex  java  servlet   |字号 订阅

1.Servlet代码

package com.fpt.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * page中上传页面的servlet
 *
 * @author 张龙
 * @version 1.0
 * @date 09-12-15
 */
public class FileUploadServlet extends HttpServlet {

 // 定义文件的上传路径

 private String uploadPath = "f:/";

 // 限制文件的上传大小

 private int maxPostSize = 100 * 1024 * 1024;

 public FileUploadServlet() {
  super();
 }

 public void destroy() {
  super.destroy();
 }

 protected void processRequest(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {
  System.out.println("Access !");
  // uploadPath=request.getSession().getServletContext().getRealPath("");
  System.out.println(uploadPath);
  response.setContentType("text/html;charset=UTF-8");
  PrintWriter out = response.getWriter();

  // 保存文件到服务器中

  DiskFileItemFactory factory = new DiskFileItemFactory();
  factory.setSizeThreshold(4096);
  ServletFileUpload upload = new ServletFileUpload(factory);
  upload.setSizeMax(maxPostSize);
  try {
   List fileItems = upload.parseRequest(request);
   Iterator iter = fileItems.iterator();
   while (iter.hasNext()) {
    FileItem item = (FileItem) iter.next();
    if (!item.isFormField()) {
     String name = item.getName();
     System.out.println(name);
     try {
      item.write(new File(uploadPath + name));
      // SaveFile s = new SaveFile();

      // s.saveFile(name);

     } catch (Exception e) {
      e.printStackTrace();
     }
    }
   }
  } catch (FileUploadException e) {
   e.printStackTrace();
   System.out.println(e.getMessage() + "结束");
  }
 }

 // <editor-fold defaultstate="collapsed"
 // desc="HttpServlet methods. Click on the + sign on the left to edit the code.">

 protected void doGet(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {
  processRequest(request, response);
 }

 protected void doPost(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {
  processRequest(request, response);
 }

 /**
  * Returns a short description of the servlet.
  */
 public String getServletInfo() {
  return "file upload";
 }

}
2.flex上传组件

<?xml version="1.0" encoding="utf-8"?>
<mx:Panel xmlns:mx="http://www.adobe.com/2006/mxml"   isPopUp="true"
    layout="vertical" width="100%" minWidth="400" height="100%" minHeight="200"
    title="上传页面" creationComplete="initCom()">
 
 <mx:Metadata>
  [Event(name="uploadComplete", type="flash.events.Event")]
  [Event(name="uploadProgress", type="flash.events.ProgressEvent")]
  [Event(name="uploadCancel", type="flash.events.Event")]
  [Event(name="uploadIOError", type="flash.events.IOErrorEvent")]
  [Event(name="uploadSecurityError", type="flash.events.SecurityErrorEvent")]
 </mx:Metadata>
 
 <mx:Script>
  <![CDATA[
   
   /*
   
   Written by:
   Dustin Andrew
   dustin@flash-dev.com
   www.flash-dev.com
   
   FileUpload
   
   Panel component for uploading files.
   (Icons from http://www.famfamfam.com)
   
   LAST UPDATED:
   12/15/06
   
   */
   
   import mx.controls.*;
   import mx.managers.*;
   import mx.events.*;
   import flash.events.*;
   import flash.net.*;
   
   private var _strUploadUrl:String;
   private var _refAddFiles:FileReferenceList;   
   private var _refUploadFile:FileReference;
   private var _arrUploadFiles:Array;
   private var _numCurrentUpload:Number = 0;           
   
   // Set uploadUrl
   public function set uploadUrl(strUploadUrl:String):void {
    _strUploadUrl = strUploadUrl;
   }
   
   // Initalize
   private function initCom():void {
    _arrUploadFiles = new Array();               
    enableUI();
    uploadCheck();
   }
   
   // Called to add file(s) for upload
   private function addFiles():void {
    _refAddFiles = new FileReferenceList();
    _refAddFiles.addEventListener(Event.SELECT, onSelectFile);
    _refAddFiles.browse();
   }
   
   // Called when a file is selected
   private function onSelectFile(event:Event):void {
    var arrFoundList:Array = new Array();
    // Get list of files from fileList, make list of files already on upload list
    for (var i:Number = 0; i < _arrUploadFiles.length; i++) {
     for (var j:Number = 0; j < _refAddFiles.fileList.length; j++) {
      if (_arrUploadFiles[i].name == _refAddFiles.fileList[j].name) {
       arrFoundList.push(_refAddFiles.fileList[j].name);
       _refAddFiles.fileList.splice(j, 1);
       j--;
      }
     }
    }
    if (_refAddFiles.fileList.length >= 1) {               
     for (var k:Number = 0; k < _refAddFiles.fileList.length; k++) {
      _arrUploadFiles.push({
       name:_refAddFiles.fileList[k].name,
       size:formatFileSize(_refAddFiles.fileList[k].size),
       file:_refAddFiles.fileList[k]});
     }
     listFiles.dataProvider = _arrUploadFiles;
     listFiles.selectedIndex = _arrUploadFiles.length - 1;
    }               
    if (arrFoundList.length >= 1) {
     Alert.show("The file(s): \n\n? " + arrFoundList.join("\n? ") + "\n\n...are already on the upload list. Please change the filename(s) or pick a different file.", "File(s) already on list");
    }
    updateProgBar();
    scrollFiles();
    uploadCheck();
   }
   
   // Called to format number to file size
   private function formatFileSize(numSize:Number):String {
    var strReturn:String;
    numSize = Number(numSize / 1000);
    strReturn = String(numSize.toFixed(1) + " KB");
    if (numSize > 1000) {
     numSize = numSize / 1000;
     strReturn = String(numSize.toFixed(1) + " MB");
     if (numSize > 1000) {
      numSize = numSize / 1000;
      strReturn = String(numSize.toFixed(1) + " GB");
     }
    }               
    return strReturn;
   }
   
   // Called to remove selected file(s) for upload
   private function removeFiles():void {
    var arrSelected:Array = listFiles.selectedIndices;
    if (arrSelected.length >= 1) {
     for (var i:Number = 0; i < arrSelected.length; i++) {
      _arrUploadFiles[Number(arrSelected[i])] = null;
     }
     for (var j:Number = 0; j < _arrUploadFiles.length; j++) {
      if (_arrUploadFiles[j] == null) {
       _arrUploadFiles.splice(j, 1);
       j--;
      }
     }
     listFiles.dataProvider = _arrUploadFiles;
     listFiles.selectedIndex = 0;                   
    }
    updateProgBar();
    scrollFiles();
    uploadCheck();
   }
   
   // Called to check if there is at least one file to upload
   private function uploadCheck():void {
    if (_arrUploadFiles.length == 0) {
     btnUpload.enabled = false;
     listFiles.verticalScrollPolicy = "off";
    } else {
     btnUpload.enabled = true;
     listFiles.verticalScrollPolicy = "on";
    }
   }
   
   // Disable UI control
   private function disableUI():void {
    btnAdd.enabled = false;
    btnRemove.enabled = false;
    btnUpload.enabled = false;
    btnCancel.enabled = true;
    listFiles.enabled = false;
    listFiles.verticalScrollPolicy = "off";
   }
   
   // Enable UI control
   private function enableUI():void {
    btnAdd.enabled = true;
    btnRemove.enabled = true;
    btnUpload.enabled = true;
    btnCancel.enabled = false;
    listFiles.enabled = true;
    listFiles.verticalScrollPolicy = "on";
   }
   
   // Scroll listFiles to selected row
   private function scrollFiles():void {
    listFiles.verticalScrollPosition = listFiles.selectedIndex;
    listFiles.validateNow();
   }
   
   // Called to upload file based on current upload number
   private function startUpload():void {
    if (_arrUploadFiles.length > 0) {
     disableUI();
     
     listFiles.selectedIndex = _numCurrentUpload;
     scrollFiles();
     
     // Variables to send along with upload
     var sendVars:URLVariables = new URLVariables();
     sendVars.action = "upload";
     
     var request:URLRequest = new URLRequest();
     request.data = sendVars;
     request.url = _strUploadUrl;
     request.method = URLRequestMethod.POST;
     _refUploadFile = new FileReference();
     _refUploadFile = listFiles.selectedItem.file;
     _refUploadFile.addEventListener(ProgressEvent.PROGRESS, onUploadProgress);
     _refUploadFile.addEventListener(Event.COMPLETE, onUploadComplete);
     _refUploadFile.addEventListener(IOErrorEvent.IO_ERROR, onUploadIoError);
     _refUploadFile.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onUploadSecurityError);
     _refUploadFile.upload(request, "file", false);
    }
   }
   
   // Cancel and clear eventlisteners on last upload
   private function clearUpload():void {
    _refUploadFile.removeEventListener(ProgressEvent.PROGRESS, onUploadProgress);
    _refUploadFile.removeEventListener(Event.COMPLETE, onUploadComplete);
    _refUploadFile.removeEventListener(IOErrorEvent.IO_ERROR, onUploadIoError);
    _refUploadFile.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onUploadSecurityError);
    _refUploadFile.cancel();
    _numCurrentUpload = 0;
    updateProgBar();
    enableUI();
   }
   
   // Called on upload cancel
   private function onUploadCanceled():void {
    clearUpload();
    dispatchEvent(new Event("uploadCancel"));
   }
   
   // Get upload progress
   private function onUploadProgress(event:ProgressEvent):void {
    var numPerc:Number = Math.round((event.bytesLoaded / event.bytesTotal) * 100);
    updateProgBar(numPerc);
    var evt:ProgressEvent = new ProgressEvent("uploadProgress", false, false, event.bytesLoaded, event.bytesTotal);
    dispatchEvent(evt);
   }
   
   // Update progBar
   private function updateProgBar(numPerc:Number = 0):void {
    var strLabel:String = (_numCurrentUpload + 1) + "/" + _arrUploadFiles.length;
    strLabel = (_numCurrentUpload + 1 <= _arrUploadFiles.length && numPerc > 0 && numPerc < 100) ? numPerc + "% - " + strLabel : strLabel;
    strLabel = (_numCurrentUpload + 1 == _arrUploadFiles.length && numPerc == 100) ? "Upload Complete - " + strLabel : strLabel;
    strLabel = (_arrUploadFiles.length == 0) ? "" : strLabel;
    progBar.label = strLabel;
    progBar.setProgress(numPerc, 100);
    progBar.validateNow();
   }
   
   // Called on upload complete
   private function onUploadComplete(event:Event):void {
    _numCurrentUpload++;               
    if (_numCurrentUpload < _arrUploadFiles.length) {
     startUpload();
    } else {
     enableUI();
     clearUpload();
     dispatchEvent(new Event("uploadComplete"));
    }
   }
   
   // Called on upload io error
   private function onUploadIoError(event:IOErrorEvent):void {
    clearUpload();
    var evt:IOErrorEvent = new IOErrorEvent("uploadIoError", false, false, event.text);
    dispatchEvent(evt);
   }
   
   // Called on upload security error
   private function onUploadSecurityError(event:SecurityErrorEvent):void {
    clearUpload();
    var evt:SecurityErrorEvent = new SecurityErrorEvent("uploadSecurityError", false, false, event.text);
    dispatchEvent(evt);
   }
   
   // Change view state
   private function changeView():void {
    currentState = (currentState == "mini") ? "" : "mini";
   }
   
  ]]>
 </mx:Script>
 
 <mx:states>
  <mx:State name="mini">
   <mx:SetProperty name="height" value="60"/>
   <mx:SetProperty name="minHeight" value="60"/>
   <mx:SetStyle target="{btnView}" name="icon" value="@Embed(&apos;imgs/icons/upload/application_put.png&apos;)"/>
  </mx:State>
 </mx:states>
 
 <mx:transitions>
  <mx:Transition fromState="*" toState="*">
   <mx:Resize target="{this}" duration="1000"/>
  </mx:Transition>
 </mx:transitions>
 
 <mx:Canvas width="100%" height="100%">
  <mx:DataGrid id="listFiles" left="0" top="0" bottom="0" right="0"
      allowMultipleSelection="true" verticalScrollPolicy="on"
      draggableColumns="false" resizableColumns="false" sortableColumns="false">
   <mx:columns>
    <mx:DataGridColumn headerText="页面名称" dataField="name" wordWrap="true"/>
    <mx:DataGridColumn headerText="页面大小" dataField="size" width="75"/>
   </mx:columns>
  </mx:DataGrid>
 </mx:Canvas>
 <mx:ControlBar horizontalAlign="center" verticalAlign="middle">
  <mx:Button id="btnAdd" toolTip="Add file(s)" click="addFiles()" icon="@Embed(&apos;imgs/icons/upload/add.png&apos;)" width="26"/>
  <mx:Button id="btnRemove" toolTip="Remove file(s)" click="removeFiles()" icon="@Embed(&apos;imgs/icons/upload/delete.png&apos;)" width="26"/>
  <mx:ProgressBar id="progBar" mode="manual" label="" labelPlacement="center" width="100%"/>
  <mx:Button id="btnCancel" toolTip="Cancel upload" icon="@Embed(&apos;imgs/icons/upload/cancel2.png&apos;)" width="26" click="onUploadCanceled()"/>
  <mx:Button label="上传" toolTip="Upload file(s)" id="btnUpload" click="startUpload()" icon="@Embed(&apos;imgs/icons/upload/bullet_go.png&apos;)"/>
  <mx:Button id="btnView" toolTip="Show/Hide file(s)" icon="@Embed(&apos;imgs/icons/upload/application_get.png&apos;)" width="26" click="changeView()"/>
 </mx:ControlBar>   
</mx:Panel>
3.flex主程序

<application>

<script>

//上传文件相关变量
   private const _strDomain:String = new String("http://192.168.1.99/");
   //private const _strUploadScript:String = new String(_strDomain + "files/FileUpload/upload.php");
   private const _strUploadScript:String = new String("http://192.168.1.99:8080/fpt/fileupload");

Security.allowDomain(_strDomain);  //安全设置

</script>

 <!--上传子页面-->
    <upload:FileUpload
     width="411" height="170"
     uploadUrl="{_strUploadScript}"
     uploadComplete="Alert.show(&apos;File(s) have been uploaded.&apos;, &apos;Upload successful&apos;)"
     uploadIOError="Alert.show(&apos;IO Error in uploading file.&apos;, &apos;Error&apos;)"
     uploadSecurityError="Alert.show(&apos;Security Error in uploading file.&apos;, &apos;Error&apos;)" x="562" y="39"/>    

</application>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值