前端jsp:
form表单要加入:
enctype="multipart/form-data" method="post"
<tr> <td>图片:<font>*</font>:</td> <td colspan="2"> <img src="<%=basePath%>candidate/printPic?pictureUrl=${candidate.image}" width="300px" height="200px" id="imgs"/> </td> <td><input class="uploadImg" type="file" name="file"></td> </tr>
js:
$("#candidate_form [name='file']").change(function() { var $file = $(this); var objUrl = $file[0].files[0]; var windowURL = window.URL || window.webkitURL; var dataURL; dataURL = windowURL.createObjectURL(objUrl); $("#candidate_form #imgs").attr("src",dataURL); });
后端:
新增候选人:
/** * 新增候选人 * @param vo * @param response * @param request */ @RequestMapping("/add") @ResponseBody @RepeatSubmitToken(removeToken = true) @RequiresPermissions(Auths.VOTING_ACTIVITY_ADD_CANDIDATE) public void addCandidate (@Valid final Candidate vo, HttpServletResponse response, final HttpServletRequest request) throws BizException{ String result = ""; if(vo.getIntroduction().length()>200){ throw new BizException("简介大于200字"); } try { if(vo.getFile()!=null && vo.getFile().getSize()!=0){ ImportUtils it = new ImportUtils(); String url = it.saveFileToRoot(vo.getFile(),image,"/candidate",1); vo.setImage(url); candidateService.addCandidate(vo); result = "success"; }else{ result = "候选人图片不能为空!"; } } catch (Exception ex) { result = "保存失败,"+ex.getMessage(); ex.printStackTrace(); } Map resultMap = new HashMap(); resultMap.put("result",result); ResponseUtils.renderHtml(response, JSON.toJSONString(resultMap), "encoding:utf-8"); }
打印图片
private String image = PropertyUtils.getPropertyValue("env", "upload.fileSavePath");
@RequestMapping("/printPic") @ResponseBody public void printPic(HttpServletRequest request,HttpServletResponse response){ String pictureUrl =request.getParameter("pictureUrl"); if(pictureUrl!=null && !"".equals(pictureUrl)){ try { String f = image+"/candidate/"+pictureUrl; response.setContentType("image/gif"); File file = new File(f); FileCopyUtils.copy(new FileInputStream(file), response.getOutputStream()); } catch (Exception e) { e.printStackTrace(); } } }