首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 媒体动画 > flex >

flex4+servlet批量下传

2012-11-21 
flex4+servlet批量上传最近刚刚学习flex4 做了一个批量上传,也不知道这个是不是真正意义上的批量上传。在这

flex4+servlet批量上传
最近刚刚学习flex4 做了一个批量上传,也不知道这个是不是真正意义上的批量上传。
在这里记录一下,以后有时间再详细改进。

UploadServlet

package upload;import java.io.File;import java.io.IOException;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Iterator;import java.util.List;import java.util.Random;import java.util.UUID;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;/** * * @author crystal */public class UploadServlet extends HttpServlet {    /**     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.     * @param request servlet request     * @param response servlet response     */    // 定义文件的上传路径// 限制文件的上传大小    private int maxPostSize = 100 * 1024 * 1024;    public UploadServlet() {        super();    }    public void destroy() {        super.destroy();    }    protected void processRequest(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        System.out.println("Access !");        response.setContentType("text/html;charset=UTF-8");//保存文件到服务器中        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 {                    String ext=name.substring(name.lastIndexOf(".")+1);                    String s = UUID.randomUUID().toString().replaceAll("-", "");                    String fileName =s+ "."+ext;                                            item.write(new File(extracted(request)+"flv\"+ fileName));                       // SaveFile s = new SaveFile();                       // s.saveFile(name);                    } catch (Exception e) {                        e.printStackTrace();                    }                }            }        } catch (FileUploadException e) {            e.printStackTrace();            System.out.println(e.getMessage() + "结束");        }    }private String extracted(HttpServletRequest request) {return request.getRealPath("/");}    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">    /**     * Handles the HTTP <code>GET</code> method.     * @param request servlet request     * @param response servlet response     */    protected void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        processRequest(request, response);    }    /**     * Handles the HTTP <code>POST</code> method.     * @param request servlet request     * @param response servlet 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 "Short description";    }    // </editor-fold>}


FileUpload.mxml
<?xml version="1.0" encoding="utf-8"?><s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"    xmlns:s="library://ns.adobe.com/flex/spark"    xmlns:mx="library://ns.adobe.com/flex/mx" fontSize="12" creationComplete="init()" currentState="selected"><s:states><s:State name="selected"/><s:State name="upload"/><s:State name="finsh"/></s:states><fx:Declarations><s:RemoteObject id="uploadid" destination="uploadid" /> </fx:Declarations><fx:Script>  <![CDATA[ import flash.events.*;import mx.collections.ArrayList;import mx.core.FlexGlobals;import upl.CustomFileReferenceList;import upl.FileReferenceListExample;private var files : FileReferenceList;[Bindable]private var fileArray : ArrayList= new ArrayList();private var serverUrl : String;private var userId : String;private var allowTypes : XML;private var fld:CustomFileReferenceList;private var   fff:FileReferenceListExample;private function init() : void {Security.allowDomain("*");var params : Object = FlexGlobals.topLevelApplication.parameters;serverUrl = encodeURI(parameters.serverUrl);userId = params.userId;fld=new CustomFileReferenceList();fld.addEventListener(Event.SELECT, showSelect);new FileReferenceListExample(fld,finsh);}private function finsh(e:Event):void{currentState="finsh";fileArray = new ArrayList();}private function upload() : void {fld.browse();}    private function showSelect(e:Event):void{for(var i:int = 0; i < fld.fileList.length; i++) {fileArray.addItem(fld.fileList[i]);}}private function onSelect(e:Event) : void {//fileArray = new ArrayList(files.fileList);for(var i:int = 0; i < fileArray.length; i++) {var file:FileReference = fileArray.source[i] as FileReference;var request: URLRequest = new URLRequest("http://localhost:8080/wb/UploadServlet")file.upload(request);//uploadid.uploadid(file.data,file.name); }currentState='upload'}protected function button1_clickHandler(event:MouseEvent):void{currentState="selected";fileArray = new ArrayList();}]]>  </fx:Script>  <s:VGroup width="577" height="363"><s:Button label="选择文件" click="upload();"  includeIn="selected"/><s:List height="114" dataProvider="{fileArray}" itemRenderer="FileShow" includeIn="selected"/><s:List dataProvider="{fileArray}" itemRenderer="FileItem" borderVisible="false" includeIn="upload"/><s:Button includeIn="selected"  click="onSelect(event)" label="上传文件"/><s:Button  includeIn="finsh" label="返回" click="button1_clickHandler(event)"/></s:VGroup></s:Application>


FileItem.mxml
<?xml version="1.0" encoding="utf-8"?><s:ItemRenderer xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" ><fx:Declarations><!-- 将非可视元素(例如服务、值对象)放在此处 --></fx:Declarations><fx:Script><![CDATA[private var _data:Object;override public function set data( obj : Object ) : void { this._data = obj; var file : FileReference = (this._data as FileReference);file.addEventListener(ProgressEvent.PROGRESS, onProgress); file.addEventListener(Event.COMPLETE, onComplete);fileName.text = file.name;}override public function get data() : Object { return this._data; }private function onProgress(e:ProgressEvent) : void {cancelBtn.visible = true;var loaded : uint = e.bytesLoaded / 1024;var total : uint =  e.bytesTotal / 1024;  var proc:uint = e.bytesLoaded / e.bytesTotal * 100;    bar.setProgress(proc, 100);bar.label = proc + "%";labelProgress.text = loaded + "kb / " + total + "kb";}private function onComplete(e:Event) : void {cancelBtn.visible = false;//ExternalInterface.call("onUploadComplete");}private function cancelUpload(e:Event) : void {var file : FileReference = (this._data as FileReference);file.cancel();}]]></fx:Script><s:layout><s:VerticalLayout/></s:layout><s:HGroup verticalAlign="middle" paddingTop="5" paddingBottom="5"><s:Label id="fileName"/><mx:ProgressBar id="bar"    labelPlacement="center"    minimum="0"    visible="true"    maximum="100"    label="0%"    direction="right"    mode="manual"    width="200"/><s:Label id="labelProgress" /><s:Button id="cancelBtn" label="取消" click="cancelUpload(event)" visible="false" /></s:HGroup></s:ItemRenderer>



FileShow.mxml
<?xml version="1.0" encoding="utf-8"?><s:ItemRenderer xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" ><s:layout><s:BasicLayout/></s:layout><fx:Declarations><!-- 将非可视元素(例如服务、值对象)放在此处 --></fx:Declarations><fx:Script><![CDATA[private var _data:Object;override public function set data( obj : Object ) : void { this._data = obj; var file : FileReference = (this._data as FileReference);fileName.text = file.name;}override public function get data() : Object { return this._data; }]]></fx:Script><s:HGroup verticalAlign="middle" paddingTop="5" paddingBottom="5"><s:Label id="fileName"/></s:HGroup></s:ItemRenderer>

热点排行