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 相关文章推荐
写了一个layout,拖动条连贯,内容区可为iframe
Aug 19 Javascript
推荐10个超棒的jQuery工具提示插件
Oct 11 Javascript
jquery插件之信息弹出框showInfoDialog(成功/错误/警告/通知/背景遮罩)
Jan 09 Javascript
jQuery插件slides实现无缝轮播图特效
Apr 17 Javascript
jQuery带进度条全屏图片轮播特效代码分享
Jun 28 Javascript
js和C# 时间日期格式转换的简单实例
May 28 Javascript
AngularJs Managing Service Dependencies详解
Sep 02 Javascript
Bootstrap下拉菜单样式
Feb 07 Javascript
基于JavaScript实现淘宝商品广告效果
Aug 10 Javascript
浅谈webpack 构建性能优化策略小结
Jun 13 Javascript
angular 服务随记小结
May 06 Javascript
微信小程序自定义modal弹窗组件的方法详解
Dec 20 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处理换行符的问题 \r\n
2013/06/13 PHP
javascript中使用replaceAll()函数实现字符替换的方法
2010/12/25 Javascript
jQuery学习笔记 操作jQuery对象 CSS处理
2012/09/19 Javascript
connect中间件session、cookie的使用方法分享
2014/06/17 Javascript
Javascript添加监听与删除监听用法详解
2014/12/19 Javascript
JavaScript如何禁止Backspace键
2015/12/02 Javascript
用Angular实时获取本地Localstorage数据,实现一个模拟后台数据登入的效果
2016/11/09 Javascript
获取当前月(季度/年)的最后一天(set相关操作及应用)
2016/12/27 Javascript
Javascript的this用法
2017/01/16 Javascript
利用JS实现简单的日期选择插件
2017/01/23 Javascript
javascript 判断当前浏览器版本并判断ie版本
2017/02/17 Javascript
JS二叉树的简单实现方法示例
2017/04/05 Javascript
JS实现复选框的全选和批量删除功能
2017/04/05 Javascript
bootstrap datetimepicker控件位置异常的解决方法
2017/11/23 Javascript
vue 实现数字滚动增加效果的实例代码
2018/07/06 Javascript
详解angular2 控制视图的封装模式
2018/12/27 Javascript
JS使用iView的Dropdown实现一个右键菜单
2019/05/06 Javascript
JavaScript实现图片放大镜效果
2019/06/27 Javascript
JS实现简单tab选项卡切换
2019/10/25 Javascript
JavaScript canvas绘制圆弧与圆形
2020/02/18 Javascript
vue滑动吸顶及锚点定位的示例代码
2020/05/10 Javascript
如何HttpServletRequest文件对象并储存
2020/08/14 Javascript
vue3使用vue-count-to组件的实现
2020/12/25 Vue.js
仅用50行Python代码实现一个简单的代理服务器
2015/04/08 Python
python中的装饰器详解
2015/04/13 Python
基于Django与ajax之间的json传输方法
2018/05/29 Python
在ubuntu16.04中将python3设置为默认的命令写法
2018/10/31 Python
使用python的turtle绘画滑稽脸实例
2019/11/21 Python
基于Pyinstaller打包Python程序并压缩文件大小
2020/05/28 Python
matplotlib bar()实现百分比堆积柱状图
2021/02/24 Python
HTML5新增加的功能详解
2016/09/05 HTML / CSS
简历中求职的个人自我评价
2013/12/03 职场文书
初中毕业生自我评价
2015/03/02 职场文书
2016优秀班主任个人先进事迹材料
2016/02/26 职场文书
导游词之广西漓江
2019/11/02 职场文书
python实现简单的名片管理系统
2021/04/26 Python