上传文件
@ResponseBody @RequestMapping("/doAdd") public Object doAdd(HttpServletRequest request, Advert advert, HttpSession session) { AjaxResult result = new AjaxResult(); try { MultipartHttpServletRequest mreq = (MultipartHttpServletRequest) request; MultipartFile mfile = mreq.getFile("advpic"); String name = mfile.getOriginalFilename();//java.jpg String extname = name.substring(name.lastIndexOf(".")); // .jpg String iconpath = UUID.randomUUID().toString() + extname; //232243343.jpg ServletContext servletContext = session.getServletContext(); String realpath = servletContext.getRealPath("/pics"); String path = realpath + "\adv\" + iconpath; mfile.transferTo(new File(path)); User user = (User) session.getAttribute(Const.LOGIN_USER); advert.setUserid(user.getId()); advert.setStatus("1"); advert.setIconpath(iconpath); int count = advertService.insertAdvert(advert); result.setSuccess(count == 1); } catch (Exception e) { e.printStackTrace(); result.setSuccess(false); result.setMessage(e.getMessage()); System.out.println(e.getStackTrace()); } return result; }
html
<form id="advertForm" method="post" action="" enctype="multipart/form-data"> <div class="form-group"> <label for="name">广告名称</label> <input type="text" class="form-control" id="name" name="name" placeholder="请输入广告名称"> </div> <div class="form-group"> <label for="url">广告地址</label> <input type="text" class="form-control" id="url" name="url" placeholder="请输入广告地址"> </div> <div class="form-group"> <label for="advpic">广告图片</label> <input type="file" class="form-control" id="advpic" name="advpic" placeholder="请输入广告图片"> </div> <button id="saveBtn" type="button" class="btn btn-success"><i class="glyphicon glyphicon-plus"></i> 新增 </button> <button type="button" class="btn btn-danger"><i class="glyphicon glyphicon-refresh"></i> 重置 </button> </form>
javascript
<script type="text/javascript"> $(function () { $(".list-group-item").click(function () { if ($(this).find("ul")) { $(this).toggleClass("tree-closed"); if ($(this).hasClass("tree-closed")) { $("ul", this).hide("fast"); } else { $("ul", this).show("fast"); } } }); }); $(function () { $("#saveBtn").click(function () { var options = { url: "${APP_PATH}/advert/doAdd.do", beforeSubmit: function () { loadingIndex = layer.msg('数据正在保存中', {icon: 6}); return true; //必须返回true,否则,请求终止. }, success: function (result) { layer.close(loadingIndex); if (result.success) { layer.msg("广告数据保存成功", {time: 1000, icon: 6}); setTimeout(function () { window.location.href = "${APP_PATH}/advert/index.htm"; }, 1000); } else { console.log(result.message); layer.msg("广告数据保存失败", {time: 1000, icon: 5, shift: 6}); } } }; $("#advertForm").ajaxSubmit(options); //异步提交 return; <%--$("#advertForm").attr("action", "${APP_PATH}/advert/doAdd.do");--%> <%--$("#advertForm").submit();--%> }); }); </script>