jquery的ajaxSubmit()异步上传图片并保存表单数据演示代码


Posted in Javascript onJune 04, 2013

(jsp需要引入 :jquery-1.9.0.js、jquery.form.js ) ,jsp页面使用的是bootstrap制作的,看不懂的标签不用管,form表单大同小异。代码比较简陋,只是为了演示使用ajaxSubmit异步上传图片及保存数据,请海含!
(参考文献:https://3water.com/shouce/jquery/jquery_api/Plugins/Form/ajaxSubmit.html)
一:web (add.jsp)

<%@page import="com.fingerknow.project.vo.UserInformation"%> 
<%@ page language="java" contentType="text/html; charset=utf-8" 
pageEncoding="utf-8"%> 
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 
<c:set var="ctx" value="${pageContext.request.contextPath }" /> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
<title>注册商圈</title> 
<link href="${ctx}/bootstrap/css/bootstrap.css" rel="stylesheet"> 
<link href="${ctx}/bootstrap/css/bootstrap-responsive.css" rel="stylesheet"> 
<link rel="stylesheet" href="${ctx}/css/bootstrap-responsive.min.css" /> 
<link rel="stylesheet" href="${ctx}/css/jquery-ui.css" /> 
<link rel="stylesheet" href="${ctx}/css/uniform.css" /> 
<link rel="stylesheet" href="${ctx}/css/select2.css" /> 
<link rel="stylesheet" href="${ctx}/css/unicorn.main.css" /> 
<link rel="stylesheet" href="${ctx}/css/common.css" /> 
<% 
response.setCharacterEncoding("utf-8");//这个是设置编码方式 
response.setContentType("text/html");//这个是设置网页类型,为文本代码 
UserInformation user=null; 
String username=""; 
Integer userId=null; 
if(request.getSession().getAttribute("userinfo")!=null){ 
user=(UserInformation)request.getSession().getAttribute("userinfo"); 
username=user.getUsername(); 
userId=user.getUserId(); 
}else{ 
username="请<a href='http://localhost:8080/fk/test/login.jsp'>登录</a>"; 
} 
%> 
</head> 
<body> 
<div class="header-inner"> 
<div class="container"> 
<div class="row"> 
<div class=" page-header clearfix"> 
<div class="span11"> <h1 class="page-header" style="background:black;"><img alt="fingerknow" src="${ctx}/images/fingerknow.png" width=""><small>中文最大的购物经验分享平台</small></h1> </div> 
<div class="span1"> <a href="#">首页</a> |<a href="#">帮助</a></div> 
</div> 
</div> 
</div> 
</div> 
<div class="container" id="businessEname_div"> 
<div class="row"> 
<div class="span1"></div> 
<div class="span10"> 
<div class="widget-box"> 
<div class="widget-title"> 
<span class="icon"> 
<i class="icon-align-justify"></i> 
</span> 
<h5>注册商圈</h5> 
</div> <div class="widget-content nopadding"> 
<form class="form-horizontal" method="post" action="${ctx}/upload/upload.do" id="uploadImgForm" enctype="multipart/form-data"> 
<div class="control-group" style="border: 0px solid red;"> 
<label class="control-label">*商圈名:</label> 
<div class="controls" style="width: 350px;border: 0px solid red;vertical-align: middle;" > 
<input type="text" name="businessName" maxlength="20" id="businessName" width="200px;"/> 
<input type="text" name="userId" maxlength="20" value="<%=userId%>" id="userId" width="200px;"/> 
<div id="businessName_error" ></div> 
</div> 
</div> 
<div class="control-group"> 
<label class="control-label">*商圈logo:</label> 
<div class="controls" style="width:350px;"> 
<input type="file" name="file" id="file"> 
<div id="file_error"></div> 
</div> 
</div> 
<div class="control-group"> 
<label class="control-label">*商圈英文名:</label> 
<div class="controls" style="width: 350px;"> 
<input type="text" name="businessEname" id="businessEname" /> 
<div id="businessEname_error"></div> 
</div> 
</div> 
<div class="form-actions"> 
<button type="button" id="imgSave" value="Validate" class="btn btn-primary">提交注册</button> 
</div> 
</form> 
</div> 
</div> 
</div> 
<div class="span1"></div> 
</div> 
</div> 
<div class="container" style="background:white;"> 
<div class="row"> 
<div class="span12" style="margin-left: 25%;"> 
<p>© 2012 fingerknow.com <span>|</span><a href="#" rel="nofollow" >隐私条款</a><span>|</span><a href="#" rel="nofollow">服务条款</a><span>|</span><a href="#" rel="nofollow" >粤ICP备12003619号-1</a></p> 
</div> 
</div> 
</div> 
<script src="${ctx}/js/jquery-1.9.0.js"></script> 
<script src="${ctx}/js/jquery.form.js"></script> 
<script type="text/javascript"> 
/** 
* 
* V1.0 
*/ 
$(document).ready(function() { 
//验证商圈名 
$("#businessName").blur(function(){ 
var businessName=$("#businessName").val(); 
if(businessName!=""){ 
$("#businessName_error").html("<img src='${ctx}/images/success_img.gif' style='width:15px;height:15px;'/>"); 
}else{ 
$("#businessName_error").attr("class","error_div").html("<img src='${ctx}/images/error_img2.gif' style='width:15px;height:15px;'/>"+"商圈名不能为空!"); 
} 
}); 
//验证商圈英文名 
$("#businessEname").blur(function(){ 
var businessEname=$("#businessEname").val(); 
if(businessEname!=""){ 
$("#businessEname_error").html("<img src='${ctx}/images/success_img.gif' style='width:15px;height:15px;'/>"); 
}else{ 
$("#businessEname_error").attr("class","error_div").html("<img src='${ctx}/images/error_img2.gif' style='width:15px;height:15px;'/>"+"商圈英文名不能为空!"); 
} 
}); 
//图片上传 及数据保存 
$("#imgSave").click(function(){ 
var ext = '.jpg.jpeg.gif.bmp.png.'; 
var f=$("#file").val(); 
if (f== "") {//先判断是否已选择了文件 
$("#file_error").attr("class","error_div").html("<img src='${ctx}/images/error_img2.gif' style='width:15px;height:15px;'/>"+"请添加商圈logo!"); 
return false; 
} 
f = f.substr(f.lastIndexOf('.') + 1).toLowerCase(); 
if (ext.indexOf('.' + f + '.') == -1) { 
$("#file_error").attr("class","error_div").html("<img src='${ctx}/images/error_img2.gif' style='width:15px;height:15px;'/>"+"图片格式不正确!"); 
return false; 
} 
var options = { 
url: "${ctx}/upload/upload.do", 
dataType: 'json', 
contentType: "application/json; charset=utf-8", 
success: function(data) { 
// 'data' is an object representing the the evaluated json data 
// 如果图片上传成功则保存表单注册数据 
if(data.status=="0"){ 
var fileName=data.fileName; 
//alert(fileName); 
var businessName=$("#businessName").val(); 
var userId=$("#userId").val(); 
var businessEname=$("#businessEname").val(); 
businessName=encodeURI(businessName); 
businessName=encodeURI(businessName); 
var urls="${ctx}/business/addBusiness.do?businessName="+businessName+"&businessPic="+fileName+"&businessEname="+businessEname+"&userId="+userId; 
$.ajax({ 
type: "post", 
url:urls , 
dataType: "json", /*这句可用可不用,没有影响*/ 
contentType: "application/json; charset=utf-8", 
success: function (data) { 
if(data.status=="0"){ 
alert("注册成功!"); 
}else{ 
alert("注册失败!原因是:"+data.message); 
} 
}, 
error: function (XMLHttpRequest, textStatus, errorThrown) { 
alert(errorThrown); 
} 
}); 
}else{ 
$("#file_error").attr("class","error_div").html("<img src='${ctx}/images/error_img2.gif' style='width:15px;height:15px;'/>"+data.message); 
} 
} 
}; 
// 提交表单 
$('#uploadImgForm').ajaxSubmit(options); 
}); 
}); 
</script> 
</body> 
</html>

二:service(FileUploadController.java ----springMVC 之controller层)
@Controller 
@RequestMapping(value = "/upload") 
public class FileUploadController { 
private Logger logger; 
@RequestMapping(value = "upload.do", method = RequestMethod.POST) 
public void fileUpload(HttpServletRequest request, HttpServletResponse response) { 
Map<String, Object> resultMap = new HashMap<String, Object>(); 
String newRealFileName = null; 
try { 
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; 
CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("file"); 
// 获得文件名: 
String realFileName = file.getOriginalFilename(); 
if(file.getSize()/1024>=5*1024){ 
resultMap.put("status", 1); 
resultMap.put("message", "图片不能大于5M"); 
}else{ 
System.out.println("获得文件名:" + realFileName); 
newRealFileName = FileUploadController.getNowTime() + realFileName.substring(realFileName.indexOf(".")); 
// 获取路径 
String ctxPath = request.getSession().getServletContext().getRealPath("//") + "//temp//"; 
// 创建文件 
File dirPath = new File(ctxPath); 
if (!dirPath.exists()) { 
dirPath.mkdir(); 
} 
File uploadFile = new File(ctxPath + newRealFileName); 
FileCopyUtils.copy(file.getBytes(), uploadFile); 
request.setAttribute("files", loadFiles(request)); 
resultMap.put("status", 0); 
resultMap.put("fileName", newRealFileName); 
} 
} catch (Exception e) { 
resultMap.put("status", 1); 
resultMap.put("message", "图片上传出错"); 
logger.info("***** 图片上传出错 *****"); 
System.out.println(e); 
} finally { 
PrintWriter out = null; 
try { 
out = response.getWriter(); 
} catch (IOException e) { 
e.printStackTrace(); 
} 
//必须设置字符编码,否则返回json会乱码 
response.setContentType("text/html;charset=UTF-8"); 
out.write(JSONSerializer.toJSON(resultMap).toString()); 
out.flush(); 
out.close(); 
} 
} 
}
Javascript 相关文章推荐
JS 获取span标签中的值的代码 支持ie与firefox
Aug 24 Javascript
Javascript自定义排序 node运行 实例
Jun 05 Javascript
AngularJS实现textarea记录只能输入规定数量的字符并显示
Apr 26 Javascript
JS中关于事件处理函数名后面是否带括号的问题
Nov 16 Javascript
JavaScript实现审核流程状态的动态显示进度条
Mar 15 Javascript
详解vue服务端渲染(SSR)初探
Jun 19 Javascript
Vue和Bootstrap的整合思路详解
Jun 30 Javascript
Vue中多个元素、组件的过渡及列表过渡的方法示例
Feb 13 Javascript
Vue自定义全局Toast和Loading的实例详解
Apr 18 Javascript
Angular6使用forRoot() 注册单一实例服务问题
Aug 27 Javascript
vue中通过使用$attrs实现组件之间的数据传递功能
Sep 01 Javascript
JavaScript中的相等操作符使用详解
Dec 21 Javascript
js调用AJAX时Get和post的乱码解决方法
Jun 04 #Javascript
jQuery调用AJAX时Get和post公用的乱码解决方法实例说明
Jun 04 #Javascript
左侧是表头的JS表格控件(自写,网上没有的)
Jun 04 #Javascript
js判断undefined变量类型使用typeof
Jun 03 #Javascript
如何使用jQUery获取选中radio对应的值(一句代码)
Jun 03 #Javascript
js+css实现增加表单可用性之提示文字
Jun 03 #Javascript
捕获浏览器关闭、刷新事件不同情况下的处理方法
Jun 02 #Javascript
You might like
php sybase_fetch_array使用方法
2014/04/15 PHP
淘宝搜索框效果实现分析
2011/03/05 Javascript
JQuery操作单选按钮以及复选按钮示例
2013/09/23 Javascript
jquery设置按钮停顿3秒不可用
2014/03/07 Javascript
jquery 插件实现多行文本框[textarea]自动高度
2015/03/04 Javascript
详解js图片轮播效果实现原理
2015/12/17 Javascript
JavaScript计算值然后把值嵌入到html中的实现方法
2016/10/29 Javascript
详解闭包解决jQuery中AJAX的外部变量问题
2017/02/22 Javascript
Vuejs 用$emit与$on来进行兄弟组件之间的数据传输通信
2017/02/23 Javascript
详解Node项目部署到云服务器上
2017/07/12 Javascript
详解vue-cli项目中用json-sever搭建mock服务器
2017/11/02 Javascript
vue实现样式之间的切换及vue动态样式的实现方法
2017/12/19 Javascript
IE8中jQuery.load()加载页面不显示的原因
2018/11/15 jQuery
简谈创建React Component的几种方式
2019/06/15 Javascript
微信小程序模板消息限制实现无限制主动推送的示例代码
2019/08/27 Javascript
[01:14:31]Secret vs VG 2018国际邀请赛淘汰赛BO3 第一场 8.23
2018/08/24 DOTA
python备份文件以及mysql数据库的脚本代码
2013/06/10 Python
python 采集中文乱码问题的完美解决方法
2016/09/27 Python
Python序列化基础知识(json/pickle)
2017/10/19 Python
python交互式图形编程实例(二)
2017/11/17 Python
Python实现的建造者模式示例
2018/08/06 Python
解决Python2.7中IDLE启动没有反应的问题
2018/11/30 Python
在Python 中同一个类两个函数间变量的调用方法
2019/01/31 Python
Python统计时间内的并发数代码实例
2019/12/28 Python
python实现交并比IOU教程
2020/04/16 Python
简单了解Python多态与属性运行原理
2020/06/15 Python
python爬虫爬取淘宝商品比价(附淘宝反爬虫机制解决小办法)
2020/12/03 Python
CSS实现定位元素居中的方法
2015/06/23 HTML / CSS
回门宴答谢词
2014/01/13 职场文书
股东出资证明书范例
2014/10/04 职场文书
2015年保卫科工作总结
2015/05/14 职场文书
篮球赛闭幕式主持词
2015/07/03 职场文书
干部考核工作总结2015
2015/07/24 职场文书
乡镇团代会开幕词
2016/03/04 职场文书
Mysql中mvcc各场景理解应用
2022/08/05 MySQL
SpringBoot前端后端分离之Nginx服务器下载安装过程
2022/08/14 Servers