Flex+Java文件上传

在研究Flex DataGrid导入excel时,用到了Flex的文件上传功能。 (参见我的Blog:http://cwfmaker.iteye.com/blog/539449) 在Adobe的Flex RIA编程环境下,是无法读取本地文件的(据我所知),但是我们可以依赖于Flex调用后台的代码实现文件上传功能,我这里是利用Flex的URLRequest来向java的Servlet传送一个Http请求(Servlet集成自HttpServlet ,已实现文件上传功能),而Servlet响应请求之后会利用Apcahe的开源Jar包(org.apache.commons.fileupload.servlet.ServletFileUpload类)完成文件的生成。 通过以上原理就可以利用Flex+java实现文件上传。(这里也是参考了网上的一些文章)

 

   java Servlet 代码

package com.yyhy.java.util;

//多文件上传的Java端的类
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.util.List;
import java.util.Iterator;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.log4j.Logger;
import org.apache.commons.lang.ObjectUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class FileUploadAction extends HttpServlet {

	// 限制文件的上传大小
	private int maxPostSize = 100 * 1024 * 1024;
	//文件上传地址
	private String uploadPath;

	public FileUploadAction() {
		//从配置文件中取得文件上传地址
		setUploadPath();
	}
	public String getUploadPath() {
		return uploadPath;
	}
	public void setUploadPath() {
		//从配置文件中取得文件上传地址
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		ServerAddress serverAddressBean=(ServerAddress)context.getBean("ServerAddressBean");
		this.uploadPath = serverAddressBean.getUploadPath().trim();
	}	
	// 文件上传
	public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException
			{
			this.doUploadAdd(request, response);
	}
	
	private void logger(String info) {
		System.out.println(info);
	}
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response)   
    throws ServletException, IOException {   
		doUploadAdd(request, response);   
     }
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response)   
    throws ServletException, IOException {   
		doUploadAdd(request, response);   
     }
	
	private void doUploadAdd(HttpServletRequest request,
			HttpServletResponse response) throws ServletException {
		logger("begin to upload");
		try {
			request.setCharacterEncoding("UTF-8");// 防止文件名称带有汉字后传到服务器乱码		
			//建立文件夹
			this.makeDir(uploadPath);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		saveFiletoServer(request,response,uploadPath);
	}
	
	private void doUploadDelete(HttpServletRequest request,HttpServletResponse response) throws ServletException 
	{
		String dirtyStr = "";//需要删除的文件名(单个文件)或文件夹名列表
		try 
		{
			if (request.getParameter("dirtyStr") != null) {
				dirtyStr=URLDecoder.decode(request.getParameter("dirtyStr"),"utf-8");//前台ENCODE,后台DECODE
				logger("删除的文件(夹)为:" + dirtyStr);
			}
		}
		catch (Exception e) {
			// TODO Auto-generated catch block
			logger(e.getMessage());
		}

		try {
			new DeleteFiles().DeleteModifyFiles(dirtyStr, uploadPath);
		} catch (Exception e) {
			logger(e.getMessage());
		}
	}
	//保存文件到服务器中
	private void saveFiletoServer(HttpServletRequest request,HttpServletResponse response,String uploadPath)
	{
		// 操作文件
		response.setContentType("text/html; charset=UTF-8");
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setSizeThreshold(1024 * 4);
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setFileSizeMax(maxPostSize);
		logger("request========" + ObjectUtils.toString(request));
		List fileItems = null;
		try {
			fileItems = upload.parseRequest(request);
			logger("============" + ObjectUtils.toString(fileItems));
			Iterator iter = fileItems.iterator();
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				log(item.toString());
				if (!item.isFormField()) {
					String name = item.getName();
					logger("上传的文件名 = " + name);
					try {
						item.write(new File(uploadPath + name));
					} catch (Exception ex) {
						logger(ex.getMessage());
					}
				}
			}
		} catch (FileUploadException ex1) {
			logger("FileUploadException->" + ex1.getMessage());
		}
	}
	// 建立文件夹路径
	private boolean makeDir(String uploadPath) {
		boolean isOK = false;
		try {
			File file = new File(uploadPath);
			file.mkdirs();
			isOK = true;
		} catch (Exception e) {
			isOK = false;
		} finally {
			return isOK;
		}
	}
	// 建立文件夹路径
	private boolean makeDirs(String uploadPath, String newDocStr) {
		boolean isOK = false;
		File file;
		String[] temp;
		try {
			temp = newDocStr.split(",");
			for (int i = 0; i < temp.length; i++) {
				file = new File(uploadPath + temp[i] + "\\");
				file.mkdirs();
			}
			isOK = true;
		} catch (Exception e) {
			isOK = false;
		} finally {
			return isOK;
		}
	}
}

   

 

    Flex前台代码:

<?xml version="1.0" encoding="utf-8"?>
<mx:TitleWindow xmlns:fx="http://ns.adobe.com/mxml/2009" 
				xmlns:s="library://ns.adobe.com/flex/spark" 
				xmlns:mx="library://ns.adobe.com/flex/halo" layout="absolute" width="400" height="300"
			    creationComplete="CreationCompletedHandler()"
			    showCloseButton="true">
	<fx:Script>
		<![CDATA[
			import mx.controls.Alert;
			import mx.events.CloseEvent;
			import mx.managers.PopUpManager;
			import mx.utils.StringUtil;
			
			[Bindable]
			private var _filename:String;

			public function get filename():String
			{
				return _filename;
			}

			public function set filename(value:String):void
			{
				_filename = value;
			}

			
			[Bindable]
			private var _file:FileReference=new FileReference(); 

			public function get file():FileReference
			{
				return _file;
			}

			public function set file(value:FileReference):void
			{
				_file = value;
			}


			[Bindable]
			private var _serveraddress:String;

			public function get serveraddress():String
			{
				return _serveraddress;
			}

			public function set serveraddress(value:String):void
			{
				_serveraddress = value;
			}

			/**creationComplete完成之后调用,获取服务器地址,建立事件监听
			 * @param null
			 * @author 陈文锋 [email protected]
			 * @return void
			 * */
			public function CreationCompletedHandler():void
			{   
				Security.allowDomain("*");
				var urlLoader:URLLoader=new URLLoader(new URLRequest("assets/conf/ServerAddressConfig.xml"));
				urlLoader.addEventListener(Event.COMPLETE,CompletedHandler);
				this.addEventListener(Event.CLOSE,TitleWindowClose);
				file.addEventListener(ProgressEvent.PROGRESS,progressHandler);
				file.addEventListener(Event.SELECT,selectedHandler);
				file.addEventListener(IOErrorEvent.IO_ERROR,ioErrorHandler);
			}
			
			private function ioErrorHandler(e:IOErrorEvent):void
			{
				Alert.show(e.toString());
			}
			
			private function progressHandler(e:ProgressEvent):void
			{
				lblProgress.text = " 已上传 " + e.bytesLoaded    
					+ " 字节,共 " + e.bytesTotal + " 字节";   
				var proc: uint = e.bytesLoaded / e.bytesTotal * 100;   
				uploadbar.setProgress(proc, 100);   
				uploadbar.label= "当前进度: " + " " + proc + "%"; 
			}
			
			/**Event事件监听处理函数,弹出上传提示窗口
			 * @param e,Event类型事件参数
			 * @author  [email protected]
			 * @return void
			 * */
			private function selectedHandler(e:Event):void
			{
				Alert.show("上传 " + file.name + " (共 "+Math.round(file.size/1024)+"KB)?",   
					"确认上传",   
					Alert.YES|Alert.NO,   
					null,   
					proceedWithUpload);
			}
			
			/**CloseEvent事件监听处理函数,访问upload的servlet服务
			 * @param e,Event类型事件参数
			 * @author  [email protected]
			 * @return void
			 * */
			private function proceedWithUpload(e:CloseEvent): void{   
				if (e.detail == Alert.YES)
				{   
					filename=file.name;
					var request:URLRequest = new URLRequest(StringUtil.trim(serveraddress));   
					try 
					{   
						file.upload(request);   
					} 
					catch (error:Error) 
					{   
						Alert.show("上传失败","错误");
					}   
					
				}   
			} 
			
			private function upload(): void{ 
				var typefiter:FileFilter=new FileFilter("Excel","*.xls");
				file.browse([typefiter]);   
			}
			
			/**CloseEvent事件监听处理函数,关闭TitleWindow弹出窗口
			 * @param e,事件参数
			 * @author  [email protected]
			 * @return void
			 * */
			private function TitleWindowClose(e:CloseEvent):void
			{
				PopUpManager.removePopUp(this);
			}
			
			/**Event事件监听处理函数,获取配置文件的文件上传路径
			 * @param e,事件参数
			 * @author  [email protected]
			 * @return void
			 * */
			private function CompletedHandler(e:Event):void
			{
				var configurationxml:XML=XML((URLLoader(e.target).data));
				serveraddress=configurationxml.filesinservername;
			}
		]]>
	</fx:Script>
	<mx:Canvas width="100%" height="100%">   
		<mx:VBox width="100%" horizontalAlign="center">   
			<mx:Label id="lblProgress" text="上传"/>   
			<mx:ProgressBar id="uploadbar" labelPlacement="bottom" themeColor="#F20D7A"   
							minimum="0" visible="true" maximum="100" label="当前进度: 0%"      
							direction="right" mode="manual" width="200"/>   
			<mx:Button label="上传文件" click="upload()"/>                
		</mx:VBox>
	</mx:Canvas> 
</mx:TitleWindow>

 

你可能感兴趣的:(java,apache,servlet,Excel,Flex)