flex上传文件

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" fontSize="12" horizontalAlign="left" initialize="init()" layout="vertical"
                viewSourceURL="srcview/index.html">
     <mx:NumberFormatter id="filesizeFormatter" useThousandsSeparator="true"/>
     <mx:Script>
         <![CDATA[
             import mx.events.CollectionEvent; 
             import mx.formatters.NumberFormatter;
             import mx.formatters.CurrencyFormatter;
             import mx.collections.ArrayCollection;
             import mx.controls.Alert;
             private var fileRefs:FileReferenceList = new FileReferenceList();
             //这个地址是我测试用的服务器地址
             private var urlrequest:URLRequest = new URLRequest("http://localhost:8080/upload/UploadFile");
             [Bindable]
             private var selectedFiles:ArrayCollection = new ArrayCollection([]);
             private var list:ArrayCollection = new ArrayCollection([]);
             private var singleThreadFiles:Array = [];
             [Bindable]
             private var useSingleThread:Boolean = true;
             private function init():void
             {
                 Security.allowDomain("*");
                 fileRefs.addEventListener(Event.SELECT, fileSelectHandler);
                 fileRefs.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
                 fileRefs.addEventListener(Event.COMPLETE, completeHandler);
                 addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);   
                 up.enabled = false;
             }
             
             private function selectFile():void
             {
                 /* fileRefs.browse([new FileFilter("Images (*.jpg, *.jpeg, *.gif, *.png)", "*.jpg;*.jpeg;*.gif;*.png"),
                     new FileFilter("所有文件(*.*)", "*.*")
                 ]); */
                 fileRefs.browse();
             }
             
             private function fileSelectHandler(event: Event):void
             {
                 for each (var f:FileReference in fileRefs.fileList)
                 {
                     selectedFiles.addItem(f);
                 }
                 up.enabled = true;
             }
             
             private function uploadFile():void
             {               
                 for each (var f:FileReference in selectedFiles)
                 {           
                     try
                     {
                         f.upload(urlrequest);
                     }
                     catch (e: Error)
                     {
                         Alert.show(e.message);
                     }
                 }
                 up.enabled = false;
             }
             
             private function ioErrorHandler(e:IOErrorEvent):void
             {
                 Alert.show(e.text);
             }
             
             private function completeHandler(e:Event):void
             {
                 Alert.show("e.target.data");
                 //img.source = e.target.data;
                 Alert.show("aa");
                 Alert.show(selectedFiles.length.toString());
             }
             
             private function showImage(e:Event): void
             {               
                 var f:FileReference = (e.target as DataGrid).selectedItem as FileReference;
                 f.addEventListener(Event.COMPLETE, completeHandler);
                 f.load();
             }
            /*  
             public function removeFile(f:FileReference): void
             {
                 var index: int = selectedFiles.getItemIndex(f);
                 if (index != -1)
                     selectedFiles.removeItemAt(index);
             } */
         ]]>
     </mx:Script>
     <mx:VBox>
         <mx:HBox width="100%">
             <!--<mx:Box width="100%" horizontalAlign="right">
                 <mx:Button label="清空" click="selectedFiles.removeAll();"/>
             </mx:Box>-->
         </mx:HBox>
         <mx:DataGrid id="files" change="/* showImage(event)  */" dataProvider="{selectedFiles}">
             <mx:columns>
                 <mx:DataGridColumn width="150" dataField="name" headerText="文件名"/>
                 <mx:DataGridColumn dataField="size" headerText="大小(字节)">
                     <mx:itemRenderer>
                         <mx:Component>
                             <mx:Label text="{outerDocument.filesizeFormatter.format(data.size)}"
                                       textAlign="right"/>
                         </mx:Component>
                     </mx:itemRenderer>
                 </mx:DataGridColumn>
                 <mx:DataGridColumn width="300" headerText="上传进度">
                     <mx:itemRenderer>
                         <mx:Component>
                             <mx:HBox fontSize="10" fontThickness="1" fontWeight="normal">
                                 <mx:Script>
                                     <![CDATA[
                                         import flash.profiler.showRedrawRegions;
                                         import mx.controls.Alert;
                                         import mx.controls.ProgressBar;
                                         private function initProgressBar(event: Event): void
                                         {
                                             //使progressbar与file关联,从而产生进度条
                                             var pb: ProgressBar = event.target as ProgressBar;
                                             pb.label = "%3%%";
                                             pb.setProgress(0, 100);
                                             var f: FileReference = data as FileReference;
                                             //使用闭包方法,更新进度条
                                             f.addEventListener(ProgressEvent.PROGRESS,
                                                 function(event: ProgressEvent): void
                                                 {
                                                     pb.setProgress(event.bytesLoaded, event.bytesTotal);
                                                 }
                                             );
                                             f.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA,
                                                 function (event: DataEvent): void
                                                 {
                                                     //服务器端一定要返回数据,否则,这个方法就不起作用了
                                                     pb.label = event.data;
                                                 }
                                             );                                           
                                         }
                                     ]]>
                                 </mx:Script>
                                 <mx:ProgressBar width="100%" label="%3%%"
                                                 creationComplete="initProgressBar(event)"
                                                 labelPlacement="center" maximum="100" minimum="0"
                                                 mode="manual" paddingLeft="5" paddingRight="5"
                                                 textAlign="left" verticalCenter="true"/>
                                 <!--<mx:LinkButton label="Cancel">
                                     <mx:click>
                                         <![CDATA[
                                         var f: FileReference = data as FileReference;
                                         f.cancel();
                                         ]]>
                                     </mx:click>
                                 </mx:LinkButton>-->
                                 <!--<mx:LinkButton label="Delete">
                                     <mx:click>
                                         <![CDATA[
                                         var f: FileReference = data as FileReference;
                                         outerDocument.removeFile(f);
                                         ]]>
                                     </mx:click>
                                 </mx:LinkButton>-->
                             </mx:HBox>
                         </mx:Component>
                     </mx:itemRenderer>
                 </mx:DataGridColumn>
             </mx:columns>
         </mx:DataGrid>
     </mx:VBox>
     <mx:HBox>
         <mx:Button id="selectFileButton" label="浏览" click="selectFile()"/>
         <mx:Button label="上传" id="up">
             <mx:click>
                 <![CDATA[
                     if(selectedFiles.length == 0) 
                     {
                         Alert.show("请选择文件");
                         return;
                     }
                     uploadFile();
                 ]]>
             </mx:click>
         </mx:Button>
         <!--<mx:CheckBox id="checkboxSingleThread" label="同时上传多个文件"
                      change="useSingleThread = !checkboxSingleThread.selected"
                      selected="{!useSingleThread}"/>-->
     </mx:HBox>
     <!--<mx:Image id="img" width="400" height="300"/>-->
</mx:Application>
package com.java;

import java.io.File;
import java.io.IOException;
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;

public class UploadFile extends HttpServlet {
    private static final long serialVersionUID = 5425836142860976977L;
    // 定义文件的上传路径
    private String uploadPath = "d:\\files\\";
    // 限制文件的上传大小
    private int maxPostSize = 100 * 1024 * 1024; // 最大100M
    public UploadFile() {
        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.setHeaderEncoding("utf-8");
        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));
                        response.getWriter().write("上传成功。");
                    } catch (Exception e) {
                        e.printStackTrace();
                        response.getWriter().write(e.getMessage());
                    }
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
            response.getWriter().write(e.getMessage());
            System.out.println(e.getMessage() + "结束");
        }
    }

    protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        File f = new File(uploadPath);
        f.mkdirs();
        processRequest(request, response);
    }

    protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        File f = new File(uploadPath);
        f.mkdirs();
        processRequest(request, response);
    }

    public String getServletInfo() {
        return "Short description";
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <display-name></display-name>    
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <servlet>  
    <servlet-name>UploadFile</servlet-name>  
    <servlet-class>com.java.UploadFile</servlet-class>  
  </servlet>  
  <servlet-mapping>  
    <servlet-name>UploadFile</servlet-name>  
    <url-pattern>/UploadFile</url-pattern>  
  </servlet-mapping>
</web-app>

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。