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 相关文章推荐
Javascript的闭包
Dec 31 Javascript
jQuery操作select下拉框的text值和value值的方法
May 31 Javascript
js实现温度计时间样式代码分享
Aug 21 Javascript
快速学习jQuery插件 Form表单插件使用方法
Dec 01 Javascript
javascript数字验证的实例代码(推荐)
Aug 20 Javascript
JavaScript 中 avalon绑定属性总结
Oct 19 Javascript
BootStrap表单验证实例代码
Jan 13 Javascript
js实现分页功能
May 24 Javascript
详解jQuery中关于Ajax的几个常用的函数
Jul 17 jQuery
JavaScript中关于base64的一些事
May 06 Javascript
vuex vue简单使用知识点总结
Aug 29 Javascript
vue-axios同时请求多个接口 等所有接口全部加载完成再处理操作
Nov 09 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中目录,文件操作详谈
2007/03/19 PHP
js实现的网站首页随机公告随机公告
2007/03/14 Javascript
使用jquery为table动态添加行的实现代码
2011/03/30 Javascript
javascript jscroll模拟html元素滚动条
2012/12/18 Javascript
JavaScript实现Flash炫光波动特效
2015/05/14 Javascript
使用AJAX实现Web页面进度条的实例分享
2016/05/06 Javascript
Vue.JS入门教程之事件监听
2016/12/01 Javascript
js实现把图片的绝对路径转为base64字符串、blob对象再上传
2016/12/29 Javascript
js图片轮播手动切换特效
2017/01/12 Javascript
Input文本框随着输入内容多少自动延伸的实现
2017/02/15 Javascript
jQuery实现遍历复选框的方法示例
2017/03/06 Javascript
vue2.0使用swiper组件实现轮播效果
2017/11/27 Javascript
JS实现点击下拉菜单把选择的内容同步到input输入框内的实例
2018/01/23 Javascript
如何将你的AngularJS1.x应用迁移至React的方法
2018/02/01 Javascript
JavaScript实现区块链
2018/03/14 Javascript
jQuery实现仿京东防抖动菜单效果示例
2018/07/06 jQuery
JavaScript判断浏览器运行环境的详细方法
2019/06/30 Javascript
nodejs使用node-xlsx生成excel的方法示例
2019/08/22 NodeJs
原生js拖拽实现图形伸缩效果
2020/02/10 Javascript
[02:53]DOTA2英雄昆卡基础教程
2013/11/25 DOTA
Django模板变量如何传递给外部js调用的方法小结
2017/07/24 Python
Python中scatter函数参数及用法详解
2017/11/08 Python
Python的多维空数组赋值方法
2018/04/13 Python
python+selenium 脚本实现每天自动登记的思路详解
2020/03/11 Python
如何在sublime编辑器中安装python
2020/05/20 Python
在pycharm中文件取消用 pytest模式打开的操作
2020/09/01 Python
Python爬虫实战案例之爬取喜马拉雅音频数据详解
2020/12/07 Python
澳大利亚连衣裙和女装在线:Esther
2017/11/11 全球购物
大学生预备党员自我评价分享
2013/11/16 职场文书
团日活动策划书
2014/02/01 职场文书
酒店管理专业毕业生求职自荐信
2014/04/28 职场文书
群众路线学习笔记范文
2014/11/06 职场文书
2014年党风建设工作总结
2014/11/19 职场文书
建筑工程材料员岗位职责
2015/04/11 职场文书
安全教育观后感
2015/06/17 职场文书
pytorch 6 batch_train 批训练操作
2021/05/28 Python