java实现头像上传 前后端

前端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();
        }
    }
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值