欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-05-17 23:32:07
(需要引入 :jquery-1.9.0.js、jquery.form.js ) ,jsp页面使用的是bootstrap制作的,看不懂的标签不用管,form表单大同小异。代码比较简陋,只是为了演示使用...

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

. 代码如下:


<%@page import="com.fingerknow.project.vo.userinformation"%>
<%@ page language="java" contenttype="text/html; charset=utf-8"
pageencoding="utf-8"%>
<%@ taglib uri="https://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" "https://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='https://localhost:8080/fk/test/login.jsp'>登录</a>";
}
%>
</head>
<body>
<p class="header-inner">
<p class="container">
<p class="row">
<p class=" page-header clearfix">
<p class="span11"> <h1 class="page-header" style="background:black;"><img alt="fingerknow" src="${ctx}/images/fingerknow.png" width=""><small>中文最大的购物经验分享平台</small></h1> </p>
<p class="span1"> <a href="#">首页</a> |<a href="#">帮助</a></p>
</p>
</p>
</p>
</p>
<p class="container" id="businessename_p">
<p class="row">
<p class="span1"></p>
<p class="span10">
<p class="widget-box">
<p class="widget-title">
<span class="icon">
<i class="icon-align-justify"></i>
</span>
<h5>注册商圈</h5>
</p>

<p class="widget-content nopadding">
<form class="form-horizontal" method="post" action="${ctx}/upload/upload.do" id="uploadimgform" enctype="multipart/form-data">
<p class="control-group" style="border: 0px solid red;">
<label class="control-label">*商圈名:</label>
<p 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;"/>
<p id="businessname_error" ></p>
</p>

</p>
<p class="control-group">
<label class="control-label">*商圈logo:</label>
<p class="controls" style="width:350px;">
<input type="file" name="file" id="file">
<p id="file_error"></p>
</p>
</p>
<p class="control-group">
<label class="control-label">*商圈英文名:</label>
<p class="controls" style="width: 350px;">
<input type="text" name="businessename" id="businessename" />
<p id="businessename_error"></p>
</p>
</p>
<p class="form-actions">
<button type="button" id="imgsave" value="validate" class="btn btn-primary">提交注册</button>
</p>
</form>
</p>
</p>
</p>
<p class="span1"></p>
</p>
</p>
<p class="container" style="background:white;">
<p class="row">
<p 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>
</p>
</p>
</p>
<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_p").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_p").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_p").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_p").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_p").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();
}
}
}