GVKun编程网logo

ajaxfileupload的使用实例(ajaxfileupload用法)

7

本文将分享ajaxfileupload的使用实例的详细内容,并且还将对ajaxfileupload用法进行详尽解释,此外,我们还将为大家带来关于$.ajaxFileUpload、$.ajaxFileU

本文将分享ajaxfileupload的使用实例的详细内容,并且还将对ajaxfileupload用法进行详尽解释,此外,我们还将为大家带来关于$.ajaxFileUpload、$.ajaxFileUpload is not a function,使用ajaxfileupload.js时提交报错、ajax-AjaxFileUpload实现ajax上传文件、ajaxfileupload的相关知识,希望对你有所帮助。

本文目录一览:

ajaxfileupload的使用实例(ajaxfileupload用法)

ajaxfileupload的使用实例(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">
		<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,required = true) multipartfile[] photo) {
		
		logger.info("后台收到参数: username = " + username + ",photo = " + photo.length);
		response.setCharacterEncoding("utf-8");
		PrintWriter pw = null;
		Map<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","存储图片失败!");
		} finally {
			pw.print(JSON.toJSONString(result));
		}
	}
	
	@RequestMapping("/ajaxfileupload3")
	public void ajaxfileupload3(HttpServletRequest request,"");
		try {
			pw = response.getWriter();
			if(photo.getSize() > 0) {
				photo.transferTo(new File(imagePath + imageName));
				logger.info("存储图片成功: " + photo.getoriginalFilename());
			}
			result.put("result",imageName);
		} catch (Exception e) {
			logger.error("存储图片失败:" + e);
			result.put("result","存储图片失败!");
		} finally {
			pw.print(JSON.toJSONString(result));
		}
	}
	
	@RequestMapping("/ajaxfileupload4")
	public void ajaxfileupload4(HttpServletRequest request,"存储图片失败!");
		} finally {
			pw.print(JSON.toJSONString(result));
		}
	}
	
	@RequestMapping("/ajaxfileupload5")
	public void ajaxfileupload5(HttpServletRequest request,"存储图片失败!");
		} 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>用户名和密码是必填项!</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,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>用户名和密码是必填项!</span>');
			} else {
				isValidate = true;
			}
			if(isValidate) {
		        $.ajaxFileUpload({
			   		url:uploadUrl,//文件选择框的id属性.
				    fileElementId:['photo1','photo2','photo3'],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,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>用户名和密码是必填项!</span>');
			} else {
				isValidate = true;
			}
			if(isValidate) {
		        $.ajaxFileUpload({
			   		url:uploadUrl,status) {
				    	if(data.result == 'success') {
				    		//及时预览.
				    		$('#img').attr('src',data.message).
				    			attr('width','100px').
				    			attr('height','100px');
				    		//继续成功的逻辑...
				    	} else {
				    		alert(data.message);
				    		//继续失败的逻辑...
				    	}
				     },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,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>用户名和密码是必填项!</span>');
			} else {
				isValidate = true;
			}
			if(isValidate) {
		        $.ajaxFileUpload({
			   		url:uploadUrl,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 = '<divhttps://www.jb51.cc/tag/aim/" target="_blank">aimageLoader(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,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>用户名和密码是必填项!</span>');
			} else {
				isValidate = true;
			}
			if(isValidate) {
		        $.ajaxFileUpload({
			   		url:uploadUrl,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">
     		<input type="file" id="photo" name="photo"onchange="document.getElementById('photoName').innerHTML=this.value"/>
	 		<input type="button"onclick="document.getElementById('photo').click()" />
	 	</div>
	 	<div id="photoName">图片文件名称</div>
		<input id="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 + '"';
		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,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",s] );
                    } else
                        jQuery.handleError(s,status);
                } catch(e){
                    status = "error";
                    jQuery.handleError(s,e);
                }
                // The request was completed
                if( s.global )
                    jQuery.event.trigger( "ajaxComplete",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,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,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,e )      {  
	    // If a local callback was specified,fire it
	    if ( s.error ) {  
	        s.error.call( s.context || s,e );  
	    }  
	    // Fire the global callback  
	    if ( s.global ) {  
	        (s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError",[xhr,s,e] );  
	    }  
    } 
});
大功告成,亲以后有什么简答的上传工作,就交给他吧!!!

$.ajaxFileUpload

$.ajaxFileUpload

我用的是这个:https://github.com/carlcarl/AjaxFileUpload

下载地址在这里:http://files.cnblogs.com/files/kissdodog/ajaxfileupload_JS_File.rar

AjaxFileUpload.js并不是一个很出名的插件,只是别人写好的放出来供大家用,原理都是创建隐藏的表单和iframe然后用JS去提交,获得返回值。

当初做了个异步上传的功能,选择它因为它的配置方式比较像jQuery的AJAX,我很喜欢。

ajaxFileUpload是一个异步上传文件的jQuery插件 语法:$.ajaxFileUpload([options])

options参数说明:

1、url           上传处理程序地址。 2,fileElementId      需要上传的文件域的ID,即“<input type="file">”的ID。 3,secureuri        是否启用安全提交,默认为false。 4,dataType        服务器返回的数据类型。可以为xml,script,json,html。如果不填写,jQuery会自动判断。 5,success        提交成功后自动执行的处理函数,参数data就是服务器返回的数据。 6,error          提交失败自动执行的处理函数。 7,data           自定义参数。这个东西比较有用,当有数据是与上传的图片相关的时候,这个东西就要用到了。 8, type           当要提交自定义参数时,这个参数要设置成post

使用方法: 1.引入ajaxfileupload.js 2.在HTML中写出

<input id="fileInput" type="file" name="file"/>

3.在js中使用$.ajaxFileUpload

// 上传
		$.ajaxFileUpload({
			url : ctx + ''calculate/upload'',
			secureuri : false,
			fileElementId : ''fileInput'',
			dataType : ''json'',
			success : function(data, status) {
				$("#progressbar").progressbar("value", 100);
				$("#download_div").show();
			},
			error : function(data, status) {
				$("#progressbar").hide();
				alert("上传文件错误");
			}
		});

4.在controller中接收

public String upload(@RequestParam(value = "file", required = false) MultipartFile file,
			HttpServletRequest request, ModelMap model)

这样接收的file就是上传的文件了

$.ajaxFileUpload is not a function,使用ajaxfileupload.js时提交报错

$.ajaxFileUpload is not a function,使用ajaxfileupload.js时提交报错

$.ajaxFileUpload is not a function,使用ajaxfileupload.js时提交报错,这是什么原因?

ajax-AjaxFileUpload实现ajax上传文件

ajax-AjaxFileUpload实现ajax上传文件

一.参考文件

1.AjaxFileUpload github官网 

二.场景

1.前端上传通过 input file标签上传文件到后端,可以用表单做,但是用ajax时不太方便,所以用这个query插件比较好。

三.举个栗子

$("#uploadButton").click(function () {
        $.ajaxFileUpload({
            url: uploadFileUrl,
            type: ''POST'',
            fileElementId: ''file'',//file input的id
            dataType: ''json'',//这里我改成大写后出现了乱码情况,小写不会
            cache: false,
            enctype: "multipart/form-data",
            traditional: true,
            success: function (data) {
                if (data != null) {                  
                    alert("创建成功");
                }
            },         
        });

    })

 

四.后端的处理可结合以下博客(SpringMvc)

https://my.oschina.net/Cubicluo/blog/894776

 

 

四.附件:以下是源码(仅供参考,这里只是摘录),只是做个备份,请去官网下载。


jQuery.extend({


    createUploadIframe: function(id, uri)
    {
        //create frame
        var frameId = ''jUploadFrame'' + id;

        if(window.ActiveXObject) {
            var io = document.createElement(''<iframe id="'' + frameId + ''" name="'' + frameId + ''" />'');
            if(typeof uri== ''boolean''){
                io.src = ''javascript:false'';
            }
            else if(typeof uri== ''string''){
                io.src = uri;
            }
        }
        else {
            var io = document.createElement(''iframe'');
            io.id = frameId;
            io.name = frameId;
        }
        io.style.position = ''absolute'';
        io.style.top = ''-1000px'';
        io.style.left = ''-1000px'';

        document.body.appendChild(io);

        return io
    },
    createUploadForm: function(id, fileElementId)
    {
        //create form
        var formId = ''jUploadForm'' + id;
        var fileId = ''jUploadFile'' + id;
        var form = $(''<form  action="" method="POST" name="'' + formId + ''" id="'' + formId + ''" enctype="multipart/form-data"></form>'');
        var oldElement = $(''#'' + fileElementId);
        var newElement = $(oldElement).clone();
        $(oldElement).attr(''id'', fileId);
        $(oldElement).before(newElement);
        $(oldElement).appendTo(form);
        //set attributes
        $(form).css(''position'', ''absolute'');
        $(form).css(''top'', ''-1200px'');
        $(form).css(''left'', ''-1200px'');
        $(form).appendTo(''body'');
        return form;
    },
    addOtherRequestsToForm: function(form,data)
    {
        // add extra parameter
        var originalElement = $(''<input type="hidden" name="" value="">'');
        for (var key in data) {
            name = key;
            value = data[key];
            var cloneElement = originalElement.clone();
            cloneElement.attr({''name'':name,''value'':value});
            $(cloneElement).appendTo(form);
        }
        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);
        if ( s.data ) form = jQuery.addOtherRequestsToForm(form,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
                    {
                        $(io).remove();
                        $(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 io = $(''#'' + frameId);
            var form = $(''#'' + formId);
            $(form).attr(''action'', s.url);
            $(form).attr(''method'', ''POST'');
            $(form).attr(''target'', frameId);
            if(form.encoding)
            {
                form.encoding = ''multipart/form-data'';
            }
            else
            {
                form.enctype = ''multipart/form-data'';
            }
            $(form).submit();

        } catch(e)
        {
            jQuery.handleError(s, xml, null, e);
        }
        if(window.attachEvent){
            document.getElementById(frameId).attachEvent(''onload'', uploadCallback);
        }
        else{
            document.getElementById(frameId).addEventListener(''load'', uploadCallback, false);
        }
        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" )
        {
            // If you add mimetype in your response,
            // you have to delete the ''<pre></pre>'' tag.
            // The pre tag in Chrome has attribute, so have to use regex to remove
            var data = r.responseText;
            var rx = new RegExp("<pre.*?>(.*?)</pre>","i");
            var am = rx.exec(data);
            //this is the desired data extracted
            var data = (am) ? am[1] : "";    //the only submatch or empty
            eval( "data = " + data );
        }
        // evaluate scripts within html
        if ( type == "html" )
            jQuery("<div>").html(data).evalScripts();
        //alert($(''param'', data).each(function(){alert($(this).attr(''value''));}));
        return data;
    }
})

 

ajaxfileupload

ajaxfileupload

原文链接:http://www.blogjava.net/sxyx2008/archive/2010/11/02/336826.html

由于项目需求,在处理文件上传时需要使用到文件的异步上传。这里使用Jquery Ajax File Uploader这个组件下载地址http://www.phpletter.com/download_project_version.php?version_id=6
服务器端采用struts2来处理文件上传。
所需环境:
jquery.js
ajaxfileupload.js
struts2所依赖的jar包
及struts2-json-plugin-2.1.8.1.jar
编写文件上传的Action

package com.ajaxfile.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings(
" serial " )
public class FileAction extends ActionSupport{

private Filefile;
private StringfileFileName;
private StringfileFileContentType;

private Stringmessage = " 你已成功上传文件 " ;

public StringgetMessage(){
return message;
}

public void setMessage(Stringmessage){
this .message = message;
}

public FilegetFile(){
return file;
}

public void setFile(Filefile){
this .file = file;
}

public StringgetFileFileName(){
return fileFileName;
}

public void setFileFileName(StringfileFileName){
this .fileFileName = fileFileName;
}

public StringgetFileFileContentType(){
return fileFileContentType;
}

public void setFileFileContentType(StringfileFileContentType){
this .fileFileContentType = fileFileContentType;
}

@SuppressWarnings(
" deprecation " )
@Override
public Stringexecute() throws Exception{

Stringpath
= ServletActionContext.getRequest().getRealPath( " /upload " );

try {
Filef
= this .getFile();
if ( this .getFileFileName().endsWith( " .exe " )){
message
= " 对不起,你上传的文件格式不允许!!! " ;
return ERROR;
}
FileInputStreaminputStream
= new FileInputStream(f);
FileOutputStreamoutputStream
= new FileOutputStream(path + " / " + this .getFileFileName());
byte []buf = new byte [ 1024 ];
int length = 0 ;
while ((length = inputStream.read(buf)) != - 1 ){
outputStream.write(buf,
0 ,length);
}
inputStream.close();
outputStream.flush();
}
catch (Exceptione){
e.printstacktrace();
message
= " 对不起,文件上传失败了!!!! " ;
}
return SUCCESS;
}

}
struts.xml
<? xmlversion="1.0"encoding="UTF-8" ?>
<! DOCTYpestrutsPUBLIC"-//ApacheSoftwareFoundation//DTDStrutsConfiguration2.1//EN""http://struts.apache.org/dtds/struts-2.1.dtd" >
< struts >
< package name ="struts2" extends ="json-default" >
< action name ="fileUploadAction" class ="com.ajaxfile.action.FileAction" >
< result type ="json" name ="success" >
< param name ="contentType" >
text/html
</ param >
</ result >
< result type ="json" name ="error" >
< param name ="contentType" >
text/html
</ param >
</ result >
</ action >
</ package >
</ struts >
注意结合Action观察struts.xml中result的配置。

contentType参数是一定要有的,否则浏览器总是提示将返回的JSON结果另存为文件,不会交给ajaxfileupload处理。这是因为struts2 JSON Plugin默认的contentType为application/json,而ajaxfileupload则要求为text/html。
文件上传的jsp页面

<% @pagelanguage = " java " contentType = " text/html;charset=UTF-8 "
pageEncoding
= " UTF-8 " %>
<! DOCTYPEhtmlPUBLIC"-//W3C//DTDHTML4.01Transitional//EN""http://www.w3.org/TR/html4/loose.dtd" >
< html >
< head >
< Meta http-equiv ="Content-Type" content ="text/html;charset=UTF-8" >
< title > Inserttitlehere </ title >
< script type ="text/javascript" src ="js/jquery.js" ></ script >
< script type ="text/javascript" src ="js/ajaxfileupload.js" ></ script >
< script type ="text/javascript" >
function ajaxFileUpload()
{

$(
" #loading " )
.ajaxStart(
function (){
$(
this ).show();
})
// 开始上传文件时显示一个图片
.ajaxComplete( function (){
$(
this ).hide();
});
// 文件上传完成将图片隐藏起来

$.ajaxFileUpload
(
{
url:'fileUploadAction.action',
// 用于文件上传的服务器端请求地址
secureuri: false , // 一般设置为false
fileElementId:'file', // 文件上传空间的id属性<inputtype="file"id="file"name="file"/>
dataType:'json', // 返回值类型一般设置为json
success: function (data,status) // 服务器成功响应处理函数
{
alert(data.message);
// 从服务器返回的json中取出message中的数据,其中message为在struts2中action中定义的成员变量

if ( typeof (data.error) != 'undefined')
{
if (data.error != '')
{
alert(data.error);
}
else
{
alert(data.message);
}
}
},
error:
function (data,status,e) // 服务器响应失败处理函数
{
alert(e);
}
}
)

return false ;

}
</ script >
</ head >
< body >
< img src ="loading.gif" id ="loading" style ="display:none;" >
< input type ="file" id ="file" name ="file" />
< br />
< input type ="button" value ="上传" onclick ="returnajaxFileUpload();" >
</ body >
</ html >
注意观察<body>中的代码,并没有form表单。只是在按钮点击的时候触发ajaxFileUpload()方法。需要注意的是js文件引入的先后顺序,ajaxfileupload.js依赖于jquery因此你知道的。

关于ajaxfileupload的使用实例ajaxfileupload用法的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于$.ajaxFileUpload、$.ajaxFileUpload is not a function,使用ajaxfileupload.js时提交报错、ajax-AjaxFileUpload实现ajax上传文件、ajaxfileupload等相关内容,可以在本站寻找。

本文标签: