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>
时间: 2024-10-11 17:08:55

flex上传文件的相关文章

Flex上传文件报“Error #2038”

1.错误描述 ioerror: [IOErrorEvent type="ioError" bubbles=false cancelable=false eventPhase=2 text="Error #2038"] 2.错误原因 可能的原因: (1)服务器连接意外中断 (2)上传的文件字节数为0 (3)无效的上传URL (4)基础验证失败 (5)上传的文件大小超过了文件大小的限制 3.解决办法

Flex上传文件Java端解决中文乱码问题

1.Flex端进行编码 public function encodeStr(str:String, charSet:String):String { var result:String =""; var bytes:ByteArray = new ByteArray(); bytes.writeMultiByte(str, charSet); for (var i:uint; i<bytes.length; i++) { result += escape(String.fromC

Flex和Servlet结合上传文件报错(一)

1.具体错误如下 一个表单域 不是一个表单域 java.io.FileNotFoundException: D:\MyEclipse\workspace\FlexFileUpload\Web\null\鏂板缓 Microsoft Word 鏂囨..docx (系统找不到指定的路径.) at java.io.FileOutputStream.open(Native Method) at java.io.FileOutputStream.<init>(FileOutputStream.java:1

Flex和Servlet结合上传文件报错(二)

1.具体报错如下 一个表单域 不是一个表单域 java.io.FileNotFoundException: D:\MyEclipse\workspace\FlexFileUpload\Web\uploadFolder\鏌卞舰鍥?xls (文件名.目录名或卷标语法不正确.) at java.io.FileOutputStream.open(Native Method) at java.io.FileOutputStream.<init>(FileOutputStream.java:179) at

Flex和Servlet结合上传文件

1.准备工作 (1)下载文件上传的组件,commons-fileupload-1.3.1.jar (2)下载文件输入输出jar,commons-io-2.4.jar (3)有关servlet的jar包,servlet-api.jar 2.正式开发 (1)新建一个web项目工程,FlexFileUpload (2)在src新建一个上传文件的servlet FlexFileUploadServlet.java: package com.you.upload.servlet; import java.

jsp借助了ajaxfileupload实现上传文件

以往我用的上传文件都是Flex写的.近期html页面须要上传页面功能. 相比之下,比flex还是要麻烦一些,问题也多一些.这里记录下: ajax上传文件,我用到了ajaxfileupload.js修正版. <form id="addAttaForm" enctype="multipart/form-data"> <div class="row"> <label for="fileUpload"&g

ajax上传文件

以往我用的上传文件都是Flex写的,最近html页面需要上传页面功能. 相比之下,比flex还是要麻烦一些,问题也多一些.这里记录下: ajax上传文件,我用到了ajaxfileupload.js修正版. <form id="addAttaForm" enctype="multipart/form-data"> <div class="row"> <label for="fileUpload"&g

upload上传文件

上传Excel文件代码demo: 下载上传js文件:bower install ng-file-uploa:引入js文件: angular.module('dc.workflow', [ 'ngFileUpload']); js代码:var data=this.data={file:null};//定义data.file为空: this.selectImage = function (file) { this.errorFileType = false; if (file[0].type !=

万家报账平台没有“上传文件”按钮的解决办法

在有的电脑没有"上传文件"的按钮? 第一步:首先检查浏览器设置. 第二步:找到IE的Internet选项菜单,开启菜单栏的根据下列方面找,如下图: 第三步:找到Internet选项后,点击,选择安全选项卡,并点击"自定义级别" 第四步:找到"将文件上载到服务器时包含本地目录路径"选择"启用".然后点击确定关闭IE,重启打开. 第五步:更新浏览器的flash版本.在百度中搜索"flash player官网"即