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.io.FileNotFoundException;
import java.io.FileOutputStream;
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.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class FlexFileUploadServlet extends HttpServlet
{
	/**
	 * @Fields serialVersionUID:序列化
	 */
	private static final long serialVersionUID = -6839362803884547766L;

	/**
	 * Constructor of the object.
	 */
	public FlexFileUploadServlet()
	{
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy()
	{
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * 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
	{
		super.doGet(request, response);
		doPost(request, response);
	}

	/**
	 * 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
	 */
	@SuppressWarnings("rawtypes")
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		/**
		 * 防止中文乱码
		 */
		response.setContentType("text/html;charset=gb2312");
		/**
		 * 设置编码格式
		 */
		response.setCharacterEncoding("utf-8");
		/**
		 * 创建一个工厂类
		 */
		FileItemFactory factory = new DiskFileItemFactory();
		/**
		 * 上传对象
		 */
		ServletFileUpload upload = new ServletFileUpload(factory);
		try {
			List items = upload.parseRequest(request);
			Iterator it = items.iterator();
			while (it.hasNext())
			{
				FileItem item = (FileItem) it.next();
				/**
				 * 判断是表单域
				 */
				if (item.isFormField())
				{
					System.out.println("一个表单域");
				}
				else
				{
					/**
					 * 处理文件上传
					 */
					System.out.println("不是一个表单域");
					String fileName = item.getName();
					byte[] data = item.get();
					/**
					 * 获取文件上传路径
					 */
					String file = getServletConfig().getInitParameter("file");
					String fileFolderName = getServletContext().getRealPath(file + "\\" + fileName);
					try {
						FileOutputStream fileOutSt = new FileOutputStream(fileFolderName);
						try
						{
							fileOutSt.write(data);
							fileOutSt.close();
						}
						catch (IOException exception)
						{
							exception.printStackTrace();
						}
					}
					catch (FileNotFoundException exception)
					{
						exception.printStackTrace();
					}
				}
			}
		}
		catch (FileUploadException exception)
		{
			exception.printStackTrace();
		}
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException
	{
		// Put your code here
	}

}

(3)配置web.xml

<?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>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>FlexFileUploadServlet</servlet-name>
    <servlet-class>com.you.upload.servlet.FlexFileUploadServlet</servlet-class>
    <init-param>
        <description>上传文件临时路径</description>
        <param-name>file</param-name>
        <param-value>file</param-value>
    </init-param>
  </servlet>

  <servlet-mapping>
    <servlet-name>FlexFileUploadServlet</servlet-name>
    <url-pattern>/FlexFileUploadServlet</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

(4)打开Flash Builder,新建Flex项目

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"
			   width="100%" height="100%" creationComplete="initHandler()"
			   fontSize="12" fontWeight="bold" accentColor="#94E1ED">
	<fx:Style>
		@namespace s "library://ns.adobe.com/flex/spark";
		@namespace mx "library://ns.adobe.com/flex/mx";
		Panel {
			borderStyle: solid;
			borderColor: #ff0000;
			borderAlpha: 0.5;
			borderThickness: 2;
			roundedBottomCorners: true;
			cornerRadius: 10;
			headerHeight: 50;
			backgroundAlpha: 0.5;
			highlightAlphas: 0.4, 0.24;
			headerColors: #cccc00, #cccc00;
			footerColors: #660033, #4217c2;
			backgroundColor: #00ffff;
			dropShadowEnabled: true;
			shadowDistance: 1;
			titleStyleName: "mypanelTitle";
		}  

		.mypanelTitle {
			letterSpacing: 1;
			color: #6600cc;
			textAlign: left;
			fontFamily: Trebuchet MS;
			fontSize: 16;
			fontWeight: bold;
			fontStyle: italic;
			textDecoration: underline;
		}
	</fx:Style>
	<fx:Script>
		<![CDATA[
			import mx.collections.ArrayCollection;
			import mx.controls.Alert;
			import mx.events.FlexEvent;

			[Bindable]
			//提示用户选择要上载的文件或用于下载的位置
			private var fileRefer:FileReference;

			[Bindable]
			//判断文件是否选中
			private var fileSelected:Boolean;

			[Bindable]
			//上传文件临时路径
			private var serverURL:String = "http://localhost:8686/FlexFileUpload/FlexFileUploadServlet";

			private var stat:Array = new Array();

			[Bindable]
			private var statusArray:ArrayCollection = new ArrayCollection();

			/**
			 * 初始化函数
			 */
			protected function initHandler():void
			{
				fileRefer = new FileReference();
				fileRefer.addEventListener(Event.SELECT, onFileSelect);
				fileRefer.addEventListener(ProgressEvent.PROGRESS,onUploadProgress);
				fileRefer.addEventListener(Event.COMPLETE, onUploadComplete);
				fileRefer.addEventListener(IOErrorEvent.IO_ERROR, onUploadError);
				fileRefer.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onUploadError);
			}

			/**
			 * 选择文件事件函数
			 */
			private function onFileSelect(event:Event):void
			{
				fileSelected = true;
				fileTxt.text = fileRefer.name;
				stat.push({status:"准备上传 "+fileTxt.text});
				statusArray = new ArrayCollection(stat);
			} 

			/**
			 * 正在上传事件函数
			 */
			private function onUploadProgress(event:ProgressEvent):void
			{
				stat.push({status:"进度.."+((event.bytesLoaded * 100) / event.bytesTotal).toString()+"%"});
				statusArray = new ArrayCollection(stat);
			} 

			/**
			 * 上传完全事件函数
			 */
			private function onUploadComplete(event:Event):void
			{
				stat.push({status:"上传成功!"});
				statusArray = new ArrayCollection(stat);
			} 

			/**
			 * 上传出现错误事件函数
			 */
			private function onUploadError(event:Event):void
			{
				if (event is IOErrorEvent)
				{
					stat.push({status:"输入输出错误: "+(event as IOErrorEvent).text.toString()});
					statusArray = new ArrayCollection(stat);
				}
				else if (event is SecurityErrorEvent)
				{
					stat.push({status:"安全错误: "+(event as IOErrorEvent).text.toString()});
					statusArray = new ArrayCollection(stat);
				}
			}

			/**
			 * 浏览按钮事件函数
			 */
			protected function uploadBtn_clickHandler(event:MouseEvent):void
			{
				fileRefer.browse();
			}

			/**
			 * 上传文件事件函数
			 */
			protected function uploadClickHandler(event:MouseEvent):void
			{
				if (!fileSelected || (urlTxt.text.length == 0))
				{
					Alert.show("请选择一个文件并选择路径");
					return;
				}
				var urlRequest:URLRequest = new URLRequest(urlTxt.text);
				fileRefer.upload(urlRequest);
			}

		]]>
	</fx:Script>
	<fx:Declarations>
		<!-- 将非可视元素(例如服务、值对象)放在此处 -->
	</fx:Declarations>

	<s:Panel title="上传文件" horizontalCenter="0" verticalCenter="0" width="400" height="400" borderColor="#FFFFFF" backgroundColor="#D1EEEE">
		<mx:VBox width="30%" height="40%" horizontalAlign="left" horizontalGap="0" paddingTop="5" paddingLeft="12">
			<mx:HBox width="100%" height="10%" horizontalAlign="left">
				<mx:VBox width="30%" height="100%" horizontalAlign="right" verticalAlign="middle">
					<s:Label text="文件名:" width="80" fontWeight="bold"></s:Label>
				</mx:VBox>
				<mx:VBox width="40%" height="100%" horizontalAlign="left">
					<s:TextInput id="fileTxt" width="200" editable="false" toolTip="选择上传文件"/>
				</mx:VBox>
				<mx:VBox width="30%" height="100%" horizontalAlign="left" verticalAlign="middle">
					<s:Button id="uploadBtn" label="浏览..." click="uploadBtn_clickHandler(event)" width="80"/>
				</mx:VBox>
			</mx:HBox>
			<mx:HBox width="100%" height="10%" horizontalAlign="left">
				<mx:VBox height="100%" width="30%" horizontalAlign="left" verticalAlign="middle">
					<s:Label text="服务器路径:" width="80" fontWeight="bold"></s:Label>
				</mx:VBox>
				<mx:VBox height="100%" width="70%" horizontalAlign="left">
					<s:TextInput id="urlTxt" width="290" text="{serverURL}"/>
				</mx:VBox>
			</mx:HBox>
			<mx:HBox height="10%" width="100%" horizontalAlign="center">
				<s:Button id="uploadBut" label="上传文件" click="uploadClickHandler(event)" enabled="{fileSelected}" />
			</mx:HBox>
			<mx:HBox height="70%" width="100%" horizontalAlign="center">
				<mx:DataGrid id="statusDG" width="100%" height="250" dataProvider="{statusArray}" variableRowHeight="true" wordWrap="true">
					<mx:columns>
						<mx:DataGridColumn dataField="status" headerText="上传文件状态" paddingLeft="0" paddingRight="0">
						</mx:DataGridColumn>
					</mx:columns>
				</mx:DataGrid>
			</mx:HBox>
		</mx:VBox>
	</s:Panel>
</s:Application>

3、运行结果

(1)初始化时

(2)上传文件

(3)上传文件之前服务器file文件夹

(4)上传文件之后服务器file文件夹

Flex和Servlet结合上传文件的更多相关文章

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

    1.详细报错例如以下 一个表单域 不是一个表单域 java.io.FileNotFoundException: D:\MyEclipse\workspace\FlexFileUpload\Web\up ...

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

    1.具体错误如下 一个表单域 不是一个表单域 java.io.FileNotFoundException: D:\MyEclipse\workspace\FlexFileUpload\Web\null ...

  3. Servlet异步上传文件

    这里需要用到插件ajaxfileupload.js,jar包:commons-fileupload-1.3.2.jar,commons-io-2.5.jar 注意红色部分的字!!!! 1.创建一个we ...

  4. Servlet 实现上传文件以及同时,写入xml格式文件和上传

    package com.isoftstone.eply.servlet; import java.io.BufferedReader; import java.io.BufferedWriter; i ...

  5. Java Servlet 接收上传文件

    在Java中使用 Servlet 来接收用户上传的文件,需要用到两个apache包,分别是 commons-fileupload 和 commons-io 包: 如果直接在doPost中,使用requ ...

  6. Android、iOS与Servlet接口上传文件和JSON串的交互

    package etcom.servlet; import java.io.File; import java.io.IOException; import java.sql.Connection; ...

  7. 使用Servlet实现上传文件功能

    1.servlet只需加上一个注释和用request.getPart来获取文件的值,这是servlet3.0的API 2.表单需要加上一个属性enctype="multipart/form- ...

  8. 上传文件,经过Zuul,中文文件名乱码解决办法

    转载请标明出处: http://blog.csdn.net/forezp/article/details/77170470 本文出自方志朋的博客 问题描述 在项目中又一个上传文件的oss服务,直接调用 ...

  9. java 网页 保存上传文件

    网页请求提交到另外一个jsp 进行处理 index.jsp <%@ page language="java" import="java.util.*" p ...

随机推荐

  1. xDB and sitecore 8 hardware Recommendations

    xDB and sitecore 8 hardware Recommendations as below: xDB hardware guidelines https://doc.sitecore.n ...

  2. BZOJ 2004: [Hnoi2010]Bus 公交线路 [DP 状压 矩阵乘法]

    传送门 题意: $n$个公交站点,$k$辆车,$1...k$是起始站,$n-k+1..n$是终点站 每个站只能被一辆车停靠一次 每辆车相邻两个停靠位置不能超过$p$ 求方案数 $n \le 10^9, ...

  3. zzcms8.2#任意用户密码重置#del.php时间盲注#复现

    00x0 引言 早上起来,发现seebug更新了一批新的洞, 发现zzcms8.2这个洞好多人在挖,于是我就默默的踏上了复现之路(要不是点进去要买详情,我何必这么折腾~) 环境:zzcms8.2(产品 ...

  4. SDN期末作业

    期末项目 代码仓库:传送门 视频:组长已经发送给朱老师 选题:负载均衡场景3 选题内容: 该拓扑是数据中心拓扑的一部分,其中h1是数据中心外的一台客户机,h2-h5是数据中心内的服务器,请根据该拓扑实 ...

  5. TensorFlow实战之Softmax Regression识别手写数字

         关于本文说明,本人原博客地址位于http://blog.csdn.net/qq_37608890,本文来自笔者于2018年02月21日 23:10:04所撰写内容(http://blog.c ...

  6. php+redis 学习 五 消息推送

    <?php header('content-type:text/html;chaeset=utf-8'); /** * redis实战 * * 发布 * * @example php publi ...

  7. python爬虫(7)——BeautifulSoup

    今天介绍一个非常好用的python爬虫库--beautifulsoup4.beautifulsoup4的中文文档参考网址是:http://beautifulsoup.readthedocs.io/zh ...

  8. Nginx:413 Request Entity Too Large解决

    最近在做给博客添加上传PDF的功能,但是在测试上传文件的过程中遇到了413 Request Entity Too Large错误.不过这个无错误是很好解决的,这个错误的出现是因为上传的文件大小超过了N ...

  9. 在CentOS 7中安装Jetty服务器

    Jetty 是一款纯Java的HTTP (Web) 服务器和Java Servlet容器. 通常在更大的网络框架中,Jetty经常用于设备间的通信,而其他Web服务器通常给"人类" ...

  10. Linux下配置SNAT上网

    局域网有一台主机A,没有公网的IP, 也就是没有办法直接连到互联网上下载东西,同时内网有另外一台主机B,有公网接入.这个时候为了让A连接到互联网,我把B设置成NAT主机,A的网关指向B.准确的来说,现 ...