ajaxfileupload的使用实例

今天简单总结一下ajaxfileupload的用法,具体实例如下:

1.上传一个文件并携带多个参数.
2.上传多个文件并携带多个参数.
  扩展:可以通过jquery扩展为添加文件选择框,去除文件选择框,而不是写死只能上传几个文件.
3.上传一个文件并携带多个参数,同时上传完成之后,及时显示.
4.上传一个文件并携带多个参数,上传之前实现预览.

5.上传一个文件,并携带多个参数.

   通过css将界面完善的更加人性化:点击图片选择文件.

项目通过maven构建,前后台通过springmvc交互数据,spring采用注解方式.

a.闲话少说先看web.xml文件,如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	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_2_5.xsd">
  <display-name>message-web</display-name>	
  	
    <!-- 配置log4j配置文件和监听器 --> 
    <context-param>
            <param-name>log4jConfigLocation</param-name>
            <param-value>classpath:log4j.properties</param-value>
    </context-param>
    <listener>
       <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>
    
  	<!-- 配置springmvc主控servlet -->
	<servlet>
		<servlet-name>springmvc</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
      		<param-name>contextConfigLocation</param-name>
      		<param-value>classpath:springmvc.xml</param-value>
   		</init-param>
	</servlet>
	<servlet-mapping>
		<servlet-name>springmvc</servlet-name>
		<url-pattern>*.mvc</url-pattern>
	</servlet-mapping>
	
	<!-- 添加字符集过滤器 -->
	<filter>
		<filter-name>encodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
</web-app>
b.接着看spring配置文件和log4j配置文件,

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans   
   		http://www.springframework.org/schema/beans/spring-beans-4.0.xsd  
        http://www.springframework.org/schema/context   
        http://www.springframework.org/schema/context/spring-context-4.0.xsd">

	<!-- 配置controller扫描 -->
	<context:component-scan base-package="com.ilucky.ajaxfileupload" />

	<!-- 设置上传文件的最大尺寸为100MB -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="maxUploadSize">
			<value>102400000</value>
		</property>
	</bean>
</beans>  
#Loggers
log4j.rootLogger=debug,console,file

#console
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Threshold = DEBUG
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%d]-%p-%l-%m%n

#file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.Append = true
log4j.appender.file.Threshold = DEBUG
log4j.appender.file.ImmediateFlush = true
log4j.appender.file.File=../webapps/ajaxfileupload.log
log4j.appender.file.MaxFileSize=2500KB
log4j.appender.file.MaxBackupIndex=20
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%d]-%p-%l-%m%n
c.然后看控制类.

package com.ilucky.ajaxfileupload;

import java.io.File;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;

/**
 * 注意:
 * 1.如果从前台传到后台的数据出现中文乱码,在web.xml文件中配置字符集过滤器.
 * 2.如果从后台传到前台的数据出现中文乱码,为response设置编码方式.
 * @author IluckySi
 * @since 20150213
 */
@Controller("uploadFileController")
@Scope("prototype")
@RequestMapping("/uploadFileController")
public class UploadFileController {

	private static Logger logger = Logger.getLogger(UploadFileController.class);
	
	@RequestMapping("/ajaxfileupload")
	public void ajaxfileupload(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "username", required = true) String username,
			@RequestParam(value = "password", required = true) String password,
			@RequestParam(value = "photo", required = true) MultipartFile photo) {
		
		logger.info("后台收到参数: username = " + username + ", password = " + password +
				", photo = " + photo.getOriginalFilename());
		response.setCharacterEncoding("utf-8");
		PrintWriter pw = null;
		Map<String, String> result = new HashMap<String, String>();
		String imagePath = request.getSession().getServletContext().getRealPath("/");
		String imageName = "image/" + photo.getOriginalFilename().replace(" ", "");
		try {
			/**
			 * 模拟位置1:前台error方法.
			 * 模拟代码:int j = 2/0;
			 */
			pw = response.getWriter();
			/**
			 * 模拟位置2:前台success方法.
			 * 模拟代码:int j = 2/0;
			 */
			if(photo.getSize() > 0) {
				photo.transferTo(new File(imagePath + imageName));
				logger.info("存储图片成功: " + photo.getOriginalFilename());
			}
			result.put("result", "success");
			result.put("message", "存储图片成功!");
		} catch (Exception e) {
			logger.error("存储图片失败:" + e);
			result.put("result", "failure");
			result.put("message", "存储图片失败!");
		} finally {
			pw.print(JSON.toJSONString(result));
		}
	}
	
	@RequestMapping("/ajaxfileupload2")
	public void ajaxfileupload2(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "username", required = true) String username,
			@RequestParam(value = "password", required = true) String password,
			@RequestParam(value = "photo", required = true) MultipartFile[] photo) {
		
		logger.info("后台收到参数: username = " + username + ", password = " + password +
				", photo = " + photo.length);
		response.setCharacterEncoding("utf-8");
		PrintWriter pw = null;
		Map<String, String> result = new HashMap<String, String>();
		String imagePath = request.getSession().getServletContext().getRealPath("/");
		try {
			pw = response.getWriter();
			for(int i = 0; i < photo.length; i++) {
				MultipartFile p = photo[i];
				if(p.getSize() > 0) {
					String imageName = "image/" + p.getOriginalFilename().replace(" ", "");
					p.transferTo(new File(imagePath + imageName));
					logger.info("存储图片成功: " + p.getOriginalFilename());
				}
			}
			result.put("result", "success");
			result.put("message", "存储图片成功!");
		} catch (Exception e) {
			logger.error("存储图片失败:" + e);
			result.put("result", "failure");
			result.put("message", "存储图片失败!");
		} finally {
			pw.print(JSON.toJSONString(result));
		}
	}
	
	@RequestMapping("/ajaxfileupload3")
	public void ajaxfileupload3(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "username", required = true) String username,
			@RequestParam(value = "password", required = true) String password,
			@RequestParam(value = "photo", required = true) MultipartFile photo) {
		
		logger.info("后台收到参数: username = " + username + ", password = " + password +
				", photo = " + photo.getOriginalFilename());
		response.setCharacterEncoding("utf-8");
		PrintWriter pw = null;
		Map<String, String> result = new HashMap<String, String>();
		String imagePath = request.getSession().getServletContext().getRealPath("/");
		String imageName = "image/" + photo.getOriginalFilename().replace(" ", "");
		try {
			pw = response.getWriter();
			if(photo.getSize() > 0) {
				photo.transferTo(new File(imagePath + imageName));
				logger.info("存储图片成功: " + photo.getOriginalFilename());
			}
			result.put("result", "success");
			result.put("message", imageName);
		} catch (Exception e) {
			logger.error("存储图片失败:" + e);
			result.put("result", "failure");
			result.put("message", "存储图片失败!");
		} finally {
			pw.print(JSON.toJSONString(result));
		}
	}
	
	@RequestMapping("/ajaxfileupload4")
	public void ajaxfileupload4(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "username", required = true) String username,
			@RequestParam(value = "password", required = true) String password,
			@RequestParam(value = "photo", required = true) MultipartFile photo) {
		
		logger.info("后台收到参数: username = " + username + ", password = " + password +
				", photo = " + photo.getOriginalFilename());
		response.setCharacterEncoding("utf-8");
		PrintWriter pw = null;
		Map<String, String> result = new HashMap<String, String>();
		String imagePath = request.getSession().getServletContext().getRealPath("/");
		String imageName = "image/" + photo.getOriginalFilename().replace(" ", "");
		try {
			pw = response.getWriter();
			if(photo.getSize() > 0) {
				photo.transferTo(new File(imagePath + imageName));
				logger.info("存储图片成功: " + photo.getOriginalFilename());
			}
			result.put("result", "success");
			result.put("message", "存储图片成功!");
		} catch (Exception e) {
			logger.error("存储图片失败:" + e);
			result.put("result", "failure");
			result.put("message", "存储图片失败!");
		} finally {
			pw.print(JSON.toJSONString(result));
		}
	}
	
	@RequestMapping("/ajaxfileupload5")
	public void ajaxfileupload5(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "username", required = true) String username,
			@RequestParam(value = "password", required = true) String password,
			@RequestParam(value = "photo", required = true) MultipartFile photo) {
		
		logger.info("后台收到参数: username = " + username + ", password = " + password +
				", photo = " + photo.getOriginalFilename());
		response.setCharacterEncoding("utf-8");
		PrintWriter pw = null;
		Map<String, String> result = new HashMap<String, String>();
		String imagePath = request.getSession().getServletContext().getRealPath("/");
		String imageName = "image/" + photo.getOriginalFilename().replace(" ", "");
		try {
			pw = response.getWriter();
			if(photo.getSize() > 0) {
				photo.transferTo(new File(imagePath + imageName));
				logger.info("存储图片成功: " + photo.getOriginalFilename());
			}
			result.put("result", "success");
			result.put("message", "存储图片成功!");
		} catch (Exception e) {
			logger.error("存储图片失败:" + e);
			result.put("result", "failure");
			result.put("message", "存储图片失败!");
		} finally {
			pw.print(JSON.toJSONString(result));
		}
	}
}
d.依次看5个实例.

<!-- 
上传一个文件并携带多个参数.
 @author IluckySi
 @since 20150213
 -->
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
     <base href="<%=basePath%>">
    <title>test</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<script src="${pageContext.request.contextPath}/js/jquery-1.11/jquery.min.js"></script>
    <script src="${pageContext.request.contextPath}/js/ajaxfileupload/ajaxfileupload.js"></script>
	<script>
	var uploadUrl = '${pageContext.request.contextPath}/uploadFileController/ajaxfileupload.mvc';
	$(function(){
		$('#upload').click(function(e){
			var username = $('#username').val();
			var password = $('#password').val();
			var isValidate = false;
			if(username == '' || password == '') {
				  $('#prompt').html('<span style="color:red">用户名和密码是必填项!</span>');
			} else {
				isValidate = true;
			}
			if(isValidate) {
		        $.ajaxFileUpload({
			   		url:uploadUrl,
				    secureuri:false,
				    //文件选择框的id属性.
				    fileElementId:'photo',
				    dataType: 'json',
				    data:{
						username:username,
						password:password	
				    }, 
				    //注意:这里的success方法代表的是前台成功接收了后台返回的数据.
				    success: function (data, status) {
				    	if(data.result == 'success') {
				    		alert(data.message);
				    		//继续成功的逻辑...
				    	} else {
				    		alert(data.message);
				    		//继续失败的逻辑...
				    	}
				     },
				     //注意:如果后前台没有成功接收后台返回的数据,则认为上传失败.
				     //换句话说如果后台的异常没有捕获到,则认为是error.
				    error: function (s, xml, status, e){
				    	console.info('上传图片失败:未知异常!');
				     } 
				});
			 }
		});
	});
	</script>
  </head>
  <body>
	<form id="form" method="post" enctype="multipart/form-data">
		<input id="username" name="username" type="text" value="请输入姓名"/>
		<input id="password" name="password" type="password" value="请输入密码"/>
		<input id="photo" name="photo" type="file"/>
		<img id="img" src=""/>
		<input id="upload" type="button" value="上传"/>
	</form>
	<div id="prompt"></div>								
  </body>
</html>
<!-- 
上传多个文件并携带多个参数.
扩展:可以通过jquery扩展为添加文件选择框,去除文件选择框,而不是写死只能上传几个文件.
 @author IluckySi
 @since 20150213
 -->
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
     <base href="<%=basePath%>">
    <title>test</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<script src="${pageContext.request.contextPath}/js/jquery-1.11/jquery.min.js"></script>
    <script src="${pageContext.request.contextPath}/js/ajaxfileupload/ajaxfileupload.js"></script>
	<script>
	var uploadUrl = '${pageContext.request.contextPath}/uploadFileController/ajaxfileupload2.mvc';
	$(function(){
		$('#upload').click(function(e){
			var username = $('#username').val();
			var password = $('#password').val();
			var isValidate = false;
			if(username == '' || password == '') {
				  $('#prompt').html('<span style="color:red">用户名和密码是必填项!</span>');
			} else {
				isValidate = true;
			}
			if(isValidate) {
		        $.ajaxFileUpload({
			   		url:uploadUrl,
				    secureuri:false,
				    //文件选择框的id属性.
				    fileElementId:['photo1', 'photo2', 'photo3'],
				    dataType: 'json',
				    data:{
						username:username,
						password:password	
				    }, 
				    //注意:这里的success方法代表的是前台成功接收了后台返回的数据.
				    success: function (data, status) {
				    	if(data.result == 'success') {
				    		alert(data.message);
				    		//继续成功的逻辑...
				    	} else {
				    		alert(data.message);
				    		//继续失败的逻辑...
				    	}
				     },
				     //注意:如果后前台没有成功接收后台返回的数据,则认为上传失败.
				     //换句话说如果后台的异常没有捕获到,则认为是error.
				    error: function (s, xml, status, e){
				    	console.info('上传图片失败:未知异常!');
				     } 
				});
			 }
		});
	});
	</script>
  </head>
  <body>
	<form id="form" method="post" enctype="multipart/form-data">
		<input id="username" name="username" type="text" value="请输入姓名"/>
		<input id="password" name="password" type="password" value="请输入密码"/>
		<input id="photo1" name="photo" type="file"/>
		<input id="photo2" name="photo" type="file"/>
		<input id="photo3" name="photo" type="file"/>
		<input id="upload" type="button" value="上传"/>
	</form>
	<div id="prompt"></div>								
  </body>
</html>
<!-- 
上传一个文件并携带多个参数,同时上传完成之后,及时显示.
 @author IluckySi
 @since 20150213
 -->
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
     <base href="<%=basePath%>">
    <title>test</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<script src="${pageContext.request.contextPath}/js/jquery-1.11/jquery.min.js"></script>
    <script src="${pageContext.request.contextPath}/js/ajaxfileupload/ajaxfileupload.js"></script>
	<script>
	var uploadUrl = '${pageContext.request.contextPath}/uploadFileController/ajaxfileupload3.mvc';
	$(function(){
		$('#upload').click(function(e){
			var username = $('#username').val();
			var password = $('#password').val();
			var isValidate = false;
			if(username == '' || password == '') {
				  $('#prompt').html('<span style="color:red">用户名和密码是必填项!</span>');
			} else {
				isValidate = true;
			}
			if(isValidate) {
		        $.ajaxFileUpload({
			   		url:uploadUrl,
				    secureuri:false,
				    //文件选择框的id属性.
				    fileElementId:'photo',
				    dataType: 'json',
				    data:{
						username:username,
						password:password	
				    }, 
				    //注意:这里的success方法代表的是前台成功接收了后台返回的数据.
				    success: function (data, status) {
				    	if(data.result == 'success') {
				    		//及时预览.
				    		$('#img').attr('src', data.message).
				    			attr('width', '100px').
				    			attr('height', '100px');
				    		//继续成功的逻辑...
				    	} else {
				    		alert(data.message);
				    		//继续失败的逻辑...
				    	}
				     },
				     //注意:如果后前台没有成功接收后台返回的数据,则认为上传失败.
				     //换句话说如果后台的异常没有捕获到,则认为是error.
				    error: function (s, xml, status, e){
				    	console.info('上传图片失败:未知异常!');
				     } 
				});
			 }
		});
	});
	</script>
  </head>
  <body>
	<form id="form" method="post" enctype="multipart/form-data">
		<input id="username" name="username" type="text" value="请输入姓名"/>
		<input id="password" name="password" type="password" value="请输入密码"/>
		<input id="photo" name="photo" type="file"/>
		<img id="img" src=""/>
		<input id="upload" type="button" value="上传"/>
	</form>
	<div id="prompt"></div>								
  </body>
</html>
<!-- 
上传一个文件并携带多个参数,上传之前实现预览.
难点:
对于Chrome,Firefox和IE10使用 FileReader来实现.
对于IE6~9使用滤镜 filter:progid:DXImageTransform.Microsoft.AlphaImageLoader来实现.
 @author IluckySi
 @since 20150213
 -->
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
     <base href="<%=basePath%>">
    <title>test</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<script src="${pageContext.request.contextPath}/js/jquery-1.11/jquery.min.js"></script>
    <script src="${pageContext.request.contextPath}/js/ajaxfileupload/ajaxfileupload.js"></script>
	<script>
	var uploadUrl = '${pageContext.request.contextPath}/uploadFileController/ajaxfileupload4.mvc';
	$(function(){
		$('#upload').click(function(e){
			var username = $('#username').val();
			var password = $('#password').val();
			var isValidate = false;
			if(username == '' || password == '') {
				  $('#prompt').html('<span style="color:red">用户名和密码是必填项!</span>');
			} else {
				isValidate = true;
			}
			if(isValidate) {
		        $.ajaxFileUpload({
			   		url:uploadUrl,
				    secureuri:false,
				    //文件选择框的id属性.
				    fileElementId:'photo',
				    dataType: 'json',
				    data:{
						username:username,
						password:password	
				    }, 
				    //注意:这里的success方法代表的是前台成功接收了后台返回的数据.
				    success: function (data, status) {
				    	if(data.result == 'success') {
				    		alert(data.message);
				    		//继续成功的逻辑...
				    	} else {
				    		alert(data.message);
				    		//继续失败的逻辑...
				    	}
				     },
				     //注意:如果后前台没有成功接收后台返回的数据,则认为上传失败.
				     //换句话说如果后台的异常没有捕获到,则认为是error.
				    error: function (s, xml, status, e){
				    	console.info('上传图片失败:未知异常!');
				     } 
				});
			 }
		});
	});
	
	//重点:图片预览.
	function preview(file){  
		var preview = document.getElementById('preview');  
		if (file.files && file.files[0]) {  
	 		var reader = new FileReader();  
	 		reader.onload = function(event){  
	 			preview.innerHTML = '<img src="' + event.target.result + '" width="100px" height="100px"/>';  
			};   
			reader.readAsDataURL(file.files[0]);  
		} else {  
			//没有用IE6~9进行测试.
			preview.innerHTML = '<div class="img" style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src=\'' + file.value + '\'"></div>';  
		}  
	}  
	</script>
  </head>
  <body>
	<form id="form" method="post" enctype="multipart/form-data">
		<input id="username" name="username" type="text" value="请输入姓名"/>
		<input id="password" name="password" type="password" value="请输入密码"/>
		<input id="photo" name="photo" type="file" onchange="preview(this)"/>
		<div id="preview"></div>
		<input id="upload" type="button" value="上传"/>
	</form>
	<div id="prompt"></div>								
  </body>
</html>
<!-- 
上传一个文件,并携带多个参数. 
<p>通过css将界面完善的更加人性化:点击图片选择文件.
 @author IluckySi
 @since 20150226
 -->
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
     <base href="<%=basePath%>">
    <title>test</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<script src="${pageContext.request.contextPath}/js/jquery-1.11/jquery.min.js"></script>
    <script src="${pageContext.request.contextPath}/js/ajaxfileupload/ajaxfileupload.js"></script>
    <style type="text/css">
	.fileDiv{
		width:100px;
		height:40px; 
		background:url(image/test.png);
		overflow:hidden;
		position:relative;
	}
	.photo{
		position:absolute;
		top:-100px;
	}
	.upFileButton{
		width:100px;
		height:40px;
		opacity:0;
		filter:alpha(opacity=0);
		cursor:pointer;
	}
	</style>
	<script>
	var uploadUrl = '${pageContext.request.contextPath}/uploadFileController/ajaxfileupload5.mvc';
	$(function(){
		$('#upload').click(function(e){
			var username = $('#username').val();
			var password = $('#password').val();
			var isValidate = false;
			if(username == '' || password == '') {
				  $('#prompt').html('<span style="color:red">用户名和密码是必填项!</span>');
			} else {
				isValidate = true;
			}
			if(isValidate) {
		        $.ajaxFileUpload({
			   		url:uploadUrl,
				    secureuri:false,
				    //文件选择框的id属性.
				    fileElementId:'photo',
				    dataType: 'json',
				    data:{
						username:username,
						password:password	
				    }, 
				    //注意:这里的success方法代表的是前台成功接收了后台返回的数据.
				    success: function (data, status) {
				    	if(data.result == 'success') {
				    		alert(data.message);
				    		//继续成功的逻辑...
				    	} else {
				    		alert(data.message);
				    		//继续失败的逻辑...
				    	}
				     },
				     //注意:如果后前台没有成功接收后台返回的数据,则认为上传失败.
				     //换句话说如果后台的异常没有捕获到,则认为是error.
				    error: function (s, xml, status, e){
				    	console.info('上传图片失败:未知异常!');
				     } 
				});
			 }
		});
	});
	</script>
  </head>
  <body>
	<form id="form" method="post" enctype="multipart/form-data">
		<input id="username" name="username" type="text" value="请输入姓名"/>
		<input id="password" name="password" type="password" value="请输入密码"/>
		<div id="fileDiv" class="fileDiv">
     		<input type="file" id="photo" name="photo" class="photo" onchange="document.getElementById('photoName').innerHTML=this.value"/>
	 		<input type="button" class="upFileButton" onclick="document.getElementById('photo').click()" />
	 	</div>
	 	<div id="photoName">图片文件名称</div>
		<input id="upload" class="upload" type="button" value="上传"/>
	</form>
	<div id="prompt"></div>	
  </body>
</html>
</p>
e.最重要的是看ajaxfileupload.js文件,此文件进行了扩展,都是从网上找到的.

// JavaScript Document
jQuery.extend({
	 createUploadIframe: function(id, uri){
		//create frame
        var frameId = 'jUploadFrame' + id;
        var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"';
		if(window.ActiveXObject){
            if(typeof uri== 'boolean'){
				iframeHtml += ' src="' + 'javascript:false' + '"';

            }
            else if(typeof uri== 'string'){
				iframeHtml += ' src="' + uri + '"';

            }	
		}
		iframeHtml += ' />';
		jQuery(iframeHtml).appendTo(document.body);
        return jQuery('#' + frameId).get(0);			
	},
    

    createUploadForm: function(id, fileElementId, data) {
    	//create form 
    	var formId = 'jUploadForm' + id;
		var fileId = 'jUploadFile' + id;
		var form = jQuery('<form  action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');	
		//使ajaxfileupload支持增加附加参数.
		if(data){
			for(var i in data){
				jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form);
			}			
		}		
		//ajaxFileupload默认是只能上传一个文件,替换如下代码地实现多个文件上传.
	    if (typeof(fileElementId) == 'string') {
	      fileElementId = [fileElementId];
	    }
	   for (var i in fileElementId) {
	      var oldElement = jQuery('#' + fileElementId[i]);
	      var newElement = jQuery(oldElement).clone();
	      jQuery(oldElement).attr('id', fileId);
	      jQuery(oldElement).before(newElement);
	      jQuery(oldElement).appendTo(form);
	
	  }
	  /*var oldElement = jQuery('#' + fileElementId);
	  var newElement = jQuery(oldElement).clone();
	  jQuery(oldElement).attr('id', fileId);
	  jQuery(oldElement).before(newElement);
	  jQuery(oldElement).appendTo(form);*/
	  //set attributes
	  jQuery(form).css('position', 'absolute');
	  jQuery(form).css('top', '-1200px');
	  jQuery(form).css('left', '-1200px');
	  jQuery(form).appendTo('body'); 
	  return form;
    },

    ajaxFileUpload: function(s) {
        // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout		
        s = jQuery.extend({}, jQuery.ajaxSettings, s);
        var id = new Date().getTime();       
		var form = jQuery.createUploadForm(id, s.fileElementId, (typeof(s.data)=='undefined'?false:s.data));
		var io = jQuery.createUploadIframe(id, s.secureuri);
		var frameId = 'jUploadFrame' + id;
		var formId = 'jUploadForm' + id;		
        // Watch for a new set of requests
        if ( s.global && ! jQuery.active++ ){
			jQuery.event.trigger( "ajaxStart" );
		}            
        var requestDone = false;
        // Create the request object
        var xml = {};   
        if ( s.global )
            jQuery.event.trigger("ajaxSend", [xml, s]);
        // Wait for a response to come back
        var uploadCallback = function(isTimeout){			
			var io = document.getElementById(frameId);
            try {	
				if(io.contentWindow){
					 xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
                	 xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
					 
				}else if(io.contentDocument){
					 xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
                	 xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
				}						
            }catch(e){
				jQuery.handleError(s, xml, null, e);
			}
            if (xml || isTimeout == "timeout"){				
                requestDone = true;
                var status;
                try {
                    status = isTimeout != "timeout" ? "success" : "error";
                    // Make sure that the request was successful or notmodified
                    if ( status != "error" ){
                        // process the data (runs the xml through httpData regardless of callback)
                        var data = jQuery.uploadHttpData(xml, s.dataType );    
                        // If a local callback was specified, fire it and pass it the data
                        if ( s.success )
                            s.success( data, status );
                        // Fire the global callback
                        if( s.global )
                            jQuery.event.trigger( "ajaxSuccess", [xml, s] );
                    } else
                        jQuery.handleError(s, xml, status);
                } catch(e){
                    status = "error";
                    jQuery.handleError(s, xml, status, e);
                }
                // The request was completed
                if( s.global )
                    jQuery.event.trigger( "ajaxComplete", [xml, s] );
                // Handle the global AJAX counter
                if ( s.global && ! --jQuery.active )
                    jQuery.event.trigger( "ajaxStop" );
                // Process result
                if ( s.complete )
                    s.complete(xml, status);
                jQuery(io).unbind();
                setTimeout(function(){	
            		try {
						jQuery(io).remove();
						jQuery(form).remove();	
						
					} catch(e){
						jQuery.handleError(s, xml, null, e);
					}									
				}, 100);
                xml = null;
            }
        };
        // Timeout checker
        if ( s.timeout > 0 ){
            setTimeout(function(){
                // Check to see if the request is still happening
                if( !requestDone ) uploadCallback( "timeout" );
            }, s.timeout);
        }
        try {
			var form = jQuery('#' + formId);
			jQuery(form).attr('action', s.url);
			jQuery(form).attr('method', 'POST');
			jQuery(form).attr('target', frameId);
            if(form.encoding){
				jQuery(form).attr('encoding', 'multipart/form-data');      			
            }
            else{	
				jQuery(form).attr('enctype', 'multipart/form-data');			
            }			
            jQuery(form).submit();

        } catch(e) {			
            jQuery.handleError(s, xml, null, e);
        }
		jQuery('#' + frameId).load(uploadCallback);
        return {abort: function () {}};	

    },

    uploadHttpData: function( r, type ) {
    	var data = !type;
        data = type == "xml" || data ? r.responseXML : r.responseText;
        // If the type is "script", eval it in global context
        if (type == "script" )
            jQuery.globalEval( data );
        // Get the JavaScript object, if JSON is used.
        if (type == "json" )
        	//针对ajaxfileupload返回json带<pre>标签解,
        	//决方案为将eval( "data = " + data );换成data = jQuery.parseJSON(jQuery(data).text());
        	//eval( "data = " + data );
        	data = jQuery.parseJSON(jQuery(data).text());
        // evaluate scripts within html
        if (type == "html" )
            jQuery("<div>").html(data).evalScripts();

        return data;
    },
    
    //针对ajaxfileupload.js结合低版本jquery报异常:TypeError: jQuery.handleError is not a function,添加如下代码.
    handleError: function( s, xhr, status, e )      {  
	    // If a local callback was specified, fire it
	    if ( s.error ) {  
	        s.error.call( s.context || s, xhr, status, e );  
	    }  
	    // Fire the global callback  
	    if ( s.global ) {  
	        (s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] );  
	    }  
    } 
});
大功告成, 亲以后有什么简答的上传工作,就交给他吧!!!


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