1.jsp
$("#cxsc").click(function(){ var bankId = $("#bankId").val(); var formdata = new FormData(); formdata.append('logo', $('#btnFile').get(0).files[0]); formdata.append('bankId', bankId); $.ajax({ type: 'POST', url: './uploadLogo', contentType : false, data : formdata, processData : false, dataType: "json", success: function (data) { $("#logoImg").attr('src','${_b}/upload/banklogo/'+data.msg); }, error : function(data) { alert('上传失败!'); } });<#if formData?exists> <#if (formData.logoImg??)> <#else> <#else>
2.controller
@RequestMapping(value = "/uploadLogo", method = {RequestMethod.POST}) public void uploadLogo( @RequestParam(value = "bankId", required = true) String bankId, @RequestParam("logo") MultipartFile logo, HttpServletRequest request, HttpServletResponse response, ModelMap model) { Json json = new Json(); BankManage bankManage = bankManageService.getById(bankId); if (bankManage != null) { try { if (!logo.isEmpty()) { String relativePath = "/upload/banklogo"; // 旧图片路径 String absolutePath = request.getSession().getServletContext().getRealPath(relativePath)+"\\"+bankManage.getLogoImg(); File oldfile = new File(absolutePath); if (oldfile.exists()) { oldfile.delete(); // 删除旧图片 } String newPath = request.getSession().getServletContext().getRealPath(relativePath)+"\\"+logo.getOriginalFilename(); File newFile = new File(newPath); logo.transferTo(newFile); bankManage.setLogoImg(logo.getOriginalFilename()); bankManageService.update(bankManage); json.setMsg(logo.getOriginalFilename()); writeJson(request, response, json); }else { json.setMsg("上传失败!"); writeJson(request, response, json); } }catch (Exception e) { e.printStackTrace(); logger.error(e); } } }