客户端代码:fileUpload.xml-------------------------------------------------------------------------------------------------
package util { import flash.events.Event; import flash.events.ProgressEvent; import flash.net.FileFilter; import flash.net.FileReference; import flash.net.URLRequest; import flash.system.Security; import mx.controls.Alert; import mx.events.CloseEvent; import org.hamcrest.mxml.collection.Array; public class ImportUtil { public function ImportUtil(){ init(); //初始化 } private static var fileRef:FileReference = new FileReference(); //上传的文件 /** * 进行初始化的操作 * **/ private static function init():void{ Security.allowDomain("*"); fileRef.addEventListener(ProgressEvent.PROGRESS, progressHandler); //上传过程中 fileRef.addEventListener(Event.SELECT, onSelect); //选择 fileRef.addEventListener(Event.COMPLETE, completeHandler); //上传完成 fileRef.addEventListener("ioError", ioerrorHandler); //错误提示 } /**** * 入口 ,调用该方法执行弹出窗口的操作 * */ public static function myupload():void{ init(); var imageTypes:FileFilter = new FileFilter("图片 (*.jpg, *.jpeg, *.gif,*.png)", "*.jpg; *.jpeg; *.gif; *.png"); var textTypes:FileFilter = new FileFilter("文本文件(*.txt)","*.txt;"); var officeType:FileFilter = new FileFilter("Office文件(*.doc, *.xls)","*.doc; *.xls"); var allTypes:Array = new Array( textTypes,officeType,imageTypes); try{ var success:Boolean = fileRef.browse(allTypes); }catch (error:Error){ Alert.show("无法浏览文件:"+error.toString()); return; } } //错误时调用的方法 private static function ioerrorHandler(event:Event):void{ Alert.show("上传文件出错:"+event.toString()); return; } //上传过程中 private static function progressHandler(event:ProgressEvent):void{ // lbProgress.text = " 已上传 " + (event.bytesLoaded/1024).toFixed(2)+ " K,共 " + (event.bytesTotal/1024).toFixed(2) + " K"; // var proc:uint = event.bytesLoaded / event.bytesTotal * 100; // progress1.setProgress(proc, 100); // progress1.label= "当前进度: " + " " + proc + "%"; } //选择 private static function onSelect(e: Event): void{ trace(fileRef.name); Alert.show("导入 " + fileRef.name + " (共 "+Math.round(fileRef.size)+" 字节)?", "确认?", Alert.YES|Alert.NO, null, selectHandler); } private static function selectHandler(event:CloseEvent):void{ if(event.detail == Alert.NO) return; var request:URLRequest = new URLRequest("http://localhost:8080/ysdsTas/UploadServlet") try { fileRef.upload(request); } catch (error:Error) { Alert.show("文件导入出错:"+error.toString()); return; } } private static function completeHandler(event:Event):void{ Alert.show("数据导入成功!"); } } }
服务器端代码:-----------------------------------------------------------------------------------------------------------
package com.ysds.util; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.io.StringReader; import java.util.Iterator; import java.util.List; import java.util.StringTokenizer; 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.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; /*** * @Program Name : ysdstas.com.ysds.util.UploadServlet.java * @Written by : rentao * @Creation Date : 2011-3-31 下午07:12:14 * @version : v1.00 * @Description : 用于上传的Servle * * * * @ModificationHistory * Who When What * -------- ---------- ------------------------------------------------ * username 2011-3-31下午07:12:14 TODO * * ***/ public class UploadServlet extends HttpServlet { private String uploadPath = "D://"; private int MAXFILESIZE = 100 * 1024 * 1024 ; /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { uploadPath = "" ; uploadPath = request.getRealPath("upload") ; //设置request编码,主要是为了处理普通输入框中的中文问题 request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter() ; DiskFileItemFactory factory = new DiskFileItemFactory(); //设置上传文件大小的上限,-1表示无上限 factory.setSizeThreshold(-1); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(MAXFILESIZE); try { //上传文件,并解析出所有的表单字段,包括普通字段和文件字段 List fileItemsList = upload.parseRequest(request) ; //下面对每个字段进行处理,分普通字段和文件字段 Iterator iter = fileItemsList.iterator() ; Boolean flag = false ; while (iter.hasNext()) { FileItem fileItem = (FileItem)iter.next() ; if(!flag){ flag = true ; uploadPath = uploadPath + "//" + new String(fileItem.getString().getBytes("ISO-8859-1"), "utf-8") ; uploadPath = UploadServlet.str_replace("//", "", uploadPath); System.out.println(uploadPath+":uploadPath"); }else { flag = true ; } //如果是普通字段 if(!fileItem.isFormField()){ //获取文件名 new String(fileItem.getString().getBytes("ISO-8859-1"), "utf-8") File file = new File(uploadPath);//创建 System.out.println("getName:"+fileItem.getName()); System.out.println("file.exists:"+file.exists()); System.out.println(fileItem.getFieldName()+":"+new String(fileItem.getString().getBytes("ISO-8859-1"), "utf-8")); if (!file.exists()) { //如果文件或没有文件夹的存在则创建次路径为准的文件夹 file.getParentFile().mkdirs(); } try { //保存文件,其实就是把缓存里的数据写到目标路径下 fileItem.write(file) ; //保存文件到服务器硬盘 response.getWriter().write("上传成功"); } catch (Exception e) { e.printStackTrace(); } } // }else { // } } } catch (Exception e) { e.printStackTrace(); System.out.println(e.getMessage()); } } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } //字符串替换的操作 public static String str_replace(String from,String to,String source) { StringBuffer bf= new StringBuffer(""); StringTokenizer st = new StringTokenizer(source,from,true); while (st.hasMoreTokens()) { String tmp = st.nextToken(); if(tmp.equals(from)) { bf.append(to); } else { bf.append(tmp); } } return bf.toString(); } }