帝王谷资源网 Design By www.wdxyy.com
(jsp需要引入 :jquery-1.9.0.js、jquery.form.js ) ,jsp页面使用的是bootstrap制作的,看不懂的标签不用管,form表单大同小异。代码比较简陋,只是为了演示使用ajaxSubmit异步上传图片及保存数据,请海含!
(参考文献:https://www.jb51.net/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="/UploadFiles/2021-04-02/fingerknow.png"><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="/UploadFiles/2021-04-02/jquery-1.9.0.js"><script src="${ctx}/js/jquery.form.js"><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();
}
}
}
(参考文献:https://www.jb51.net/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="/UploadFiles/2021-04-02/fingerknow.png"><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="/UploadFiles/2021-04-02/jquery-1.9.0.js"><script src="${ctx}/js/jquery.form.js"><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();
}
}
}
标签:
ajaxSubmit,异步上传
帝王谷资源网 Design By www.wdxyy.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
帝王谷资源网 Design By www.wdxyy.com
暂无评论...
更新日志
2024年10月30日
2024年10月30日
- 群星《乘风2024 第6期》[FLAC/分轨][170.72MB]
- 陈立强1995-我爱你胜过这世界[福茂][WAV+CUE]
- 群星-《2014年十大发烧唱片精选HQCD》[低速原抓WAV+CUE]
- 群星2013-青春缤纷辑压箱宝大公开3CD2[新加坡限量版][WAV整轨]
- 林育群.2013-BalladShow(日本版)【环球】【WAV+CUE】
- 陈加洛.1992-痛到感觉不到【宝丽金】【WAV+CUE】
- 群星.2023-宿命之敌电视剧原声带【韶愔音乐】【FLAC分轨】
- 東京事変-大発見[FLAC+CUE]
- 椎名林檎-三文ゴシップ[FLAC+CUE]
- 2024年08月04日
- 裘德《裘德「最后的水族馆」演唱会LIVE》[320K/MP3][228.89MB]
- 裘德《裘德「最后的水族馆」演唱会LIVE》[24bit 48kHz][FLAC/分轨][2.08G]
- 基因三重奏《如果你什么都不说 音乐会现场录音》[320K/MP3][145.37MB]
- 孟庭苇.1996-月亮说话(2020环球24KGOLD限量版)【上华】【WAV+CUE】
- 群星.1997-新艺宝优质音响系列·国语精选监听版【新艺宝】【WAV+CUE】