javascript

位置:IT落伍者 >> javascript >> 浏览文章

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


发布日期:2023年02月13日
 
jquery的ajaxSubmit()异步上传图片并保存表单数据演示代码

web (addjsp)

代码如下:<%@page import="comfingerknowprojectvoUserInformation"%><%@ page language="java" contentType="text/html; charset=utf"pageEncoding="utf"%><%@ taglib uri="%><c:set var="ctx" value="${pageContextrequestcontextPath }" /><!DOCTYPE html PUBLIC "//WC//DTD HTML Transitional//EN" "<html><head><meta httpequiv="ContentType" content="text/html; charset=utf"><title>注册商圈</title><link href="${ctx}/bootstrap/css/bootstrapcss" rel="stylesheet"><link href="${ctx}/bootstrap/css/bootstrapresponsivecss" rel="stylesheet"><link rel="stylesheet" href="${ctx}/css/bootstrapresponsivemincss" /><link rel="stylesheet" href="${ctx}/css/jqueryuicss" /><link rel="stylesheet" href="${ctx}/css/uniformcss" /><link rel="stylesheet" href="${ctx}/css/selectcss" /><link rel="stylesheet" href="${ctx}/css/unicornmaincss" /><link rel="stylesheet" href="${ctx}/css/commoncss" /><%responsesetCharacterEncoding("utf");//这个是设置编码方式responsesetContentType("text/html");//这个是设置网页类型为文本代码UserInformation user=null;String username="";Integer userId=null;if(requestgetSession()getAttribute("userinfo")!=null){user=(UserInformation)requestgetSession()getAttribute("userinfo");username=usergetUsername();userId=usergetUserId();}else{username="请<a >登录</a>";}%></head><body><div class="headerinner"><div class="container"><div class="row"><div class=" pageheader clearfix"><div class="span"> <h class="pageheader" style="background:black;"><img alt="fingerknow" src="${ctx}/images/fingerknowpng" width=""><small>中文最大的购物经验分享平台</small></h> </div><div class="span"> <a href="#">首页</a> |<a href="#">帮助</a></div></div></div></div></div><div class="container" id="businessEname_div"><div class="row"><div class="span"></div><div class="span"><div class="widgetbox"><div class="widgettitle"><span class="icon"><i class="iconalignjustify"></i></span><h>注册商圈</h></div><div class="widgetcontent nopadding"><form class="formhorizontal" method="post" action="${ctx}/upload/uploaddo" id="uploadImgForm" enctype="multipart/formdata"><div class="controlgroup" style="border: px solid red;"><label class="controllabel">*商圈名</label><div class="controls" style="width: px;border: px solid red;verticalalign: middle;" ><input type="text" name="businessName" maxlength="" id="businessName" width="px;"/><input type="text" name="userId" maxlength="" value="<%=userId%>" id="userId" width="px;"/><div id="businessName_error" ></div></div></div><div class="controlgroup"><label class="controllabel">*商圈logo</label><div class="controls" style="width:px;"><input type="file" name="file" id="file"><div id="file_error"></div></div></div><div class="controlgroup"><label class="controllabel">*商圈英文名</label><div class="controls" style="width: px;"><input type="text" name="businessEname" id="businessEname" /><div id="businessEname_error"></div></div></div><div class="formactions"><button type="button" id="imgSave" value="Validate" class="btn btnprimary">提交注册</button></div></form></div></div></div><div class="span"></div></div></div><div class="container" style="background:white;"><div class="row"><div class="span" style="marginleft: %;"><p>© fingerknowcom <span>|</span><a href="#" rel="nofollow" >隐私条款</a><span>|</span><a href="#" rel="nofollow">服务条款</a><span>|</span><a href="#" rel="nofollow" >粤ICP备</a></p></div></div></div><script src="${ctx}/js/jqueryjs"></script><script src="${ctx}/js/jqueryformjs"></script><script type="text/javascript">/**** V*/$(document)ready(function() {//验证商圈名$("#businessName")blur(function(){var businessName=$("#businessName")val();if(businessName!=""){$("#businessName_error")html("<img src=${ctx}/images/success_imggif style=width:px;height:px;/>");}else{$("#businessName_error")attr("class""error_div")html("<img src=${ctx}/images/error_imggif style=width:px;height:px;/>"+"商圈名不能为空!");}});//验证商圈英文名$("#businessEname")blur(function(){var businessEname=$("#businessEname")val();if(businessEname!=""){$("#businessEname_error")html("<img src=${ctx}/images/success_imggif style=width:px;height:px;/>");}else{$("#businessEname_error")attr("class""error_div")html("<img src=${ctx}/images/error_imggif style=width:px;height:px;/>"+"商圈英文名不能为空!");}});//图片上传 及数据保存$("#imgSave")click(function(){var ext = jpgjpeggifbmppng;var f=$("#file")val();if (f== "") {//先判断是否已选择了文件$("#file_error")attr("class""error_div")html("<img src=${ctx}/images/error_imggif style=width:px;height:px;/>"+"请添加商圈logo!");return false;}f = fsubstr(flastIndexOf() + )toLowerCase();if (extindexOf( + f + ) == ) {$("#file_error")attr("class""error_div")html("<img src=${ctx}/images/error_imggif style=width:px;height:px;/>"+"图片格式不正确!");return false;}var options = {url: "${ctx}/upload/uploaddo"dataType: jsoncontentType: "application/json; charset=utf"success: function(data) {// data is an object representing the the evaluated json data// 如果图片上传成功则保存表单注册数据if(datastatus==""){var fileName=datafileName;//alert(fileName);var businessName=$("#businessName")val();var userId=$("#userId")val();var businessEname=$("#businessEname")val();businessName=encodeURI(businessName);businessName=encodeURI(businessName);var urls="${ctx}/business/addBusinessdo?businessName="+businessName+"&businessPic="+fileName+"&businessEname="+businessEname+"&userId="+userId;$ajax({type: "post"url:urls dataType: "json" /*这句可用可不用没有影响*/contentType: "application/json; charset=utf"success: function (data) {if(datastatus==""){alert("注册成功!");}else{alert("注册失败!原因是"+datamessage);}}error: function (XMLHttpRequest textStatus errorThrown) {alert(errorThrown);}});}else{$("#file_error")attr("class""error_div")html("<img src=${ctx}/images/error_imggif style=width:px;height:px;/>"+datamessage);}}};// 提交表单$(#uploadImgForm)ajaxSubmit(options);});});</script></body></html>二service(FileUploadControllerjava springMVC 之controller层)代码如下:@Controller@RequestMapping(value = "/upload")public class FileUploadController {private Logger logger;@RequestMapping(value = "uploaddo" method = RequestMethodPOST)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) multipartRequestgetFile("file");// 获得文件名String realFileName = filegetOriginalFilename();if(filegetSize()/>=*){resultMapput("status" );resultMapput("message" "图片不能大于M");}else{Systemoutprintln("获得文件名" + realFileName);newRealFileName = FileUploadControllergetNowTime() + realFileNamesubstring(realFileNameindexOf(""));// 获取路径String ctxPath = requestgetSession()getServletContext()getRealPath("//") + "//temp//";// 创建文件File dirPath = new File(ctxPath);if (!dirPathexists()) {dirPathmkdir();}File uploadFile = new File(ctxPath + newRealFileName);FileCopyUtilscopy(filegetBytes() uploadFile);requestsetAttribute("files" loadFiles(request));resultMapput("status" );resultMapput("fileName" newRealFileName);}} catch (Exception e) {resultMapput("status" );resultMapput("message" "图片上传出错");loggerinfo("***** 图片上传出错 *****");Systemoutprintln(e);} finally {PrintWriter out = null;try {out = responsegetWriter();} catch (IOException e) {eprintStackTrace();}//必须设置字符编码否则返回json会乱码responsesetContentType("text/html;charset=UTF");outwrite(JSONSerializertoJSON(resultMap)toString());outflush();outclose();}}}

上一篇:解决js UTF-8传参到GBK页面乱码问题

下一篇:javascript实现TreeView 无刷新展开的实例代码