首页 > Web开发 > 详细

简单的上传文件

时间:2016-03-22 19:10:28      阅读:302      评论:0      收藏:0      [点我收藏+]

前端代码:

     <tr>
            <td align="right">上传头像:</td>
            <td>
                 <form method="post" enctype="multipart/form-data" action="/member/uploadHeadPhoto.do" id="uploadHeadPhotoForm"> 
                       <input type="file" name="headPhotoFile" id="headPhotoFile"/><br/>
</form> </td> </tr>
     <tr><td><a href="javascript:void(0);" onclick="save();">保存</a></td></tr>

js:

 function save(){ 
  //判断图片类型  
  var headPhotoFile = $("#headPhotoFile").val(); if(headPhotoFile){ if(!/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(headPhotoFile)){ alert("图片类型必须是gif,jpeg,jpg,png中的一种"); return; } }
  $("#uploadHeadPhotoForm").submit();

  }

 

 

后端代码:   

    @RequestMapping(value = "/uploadHeadPhoto.do", method = RequestMethod.POST)
public String uploadHeadPhoto(@RequestParam("headPhotoFile") MultipartFile headPhotoFile, @RequestParam(value = "userid") Long userId, HttpServletRequest request,HttpServletResponse response) { if(!headPhotoFile.isEmpty()){ try { byte[] bytes = headPhotoFile.getBytes(); String path = request.getSession().getServletContext().getRealPath("/"); String originalFilename = headPhotoFile.getOriginalFilename(); String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "." + originalFilename.split("\\.")[1]; String relativePath = "/项目路径/images/pictures/" + fileName; BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(path + relativePath))); stream.write(bytes); stream.close(); //获取此用户原来的头像 Member member = memberService.getMember(userId); if(member != null && !"".equals(member.getHeadphoto()) && member.getHeadphoto() != null){ String oldPath = path + "/项目路径/images/pictures/" + member.getHeadphoto(); deleteFile(oldPath); //删除原来的用户头像 } System.out.println("上传头像成功"); } catch (IOException e) { // TODO Auto-generated catch block System.out.println("上传头像失败"); e.printStackTrace(); } } return "redirect:项目跳转路径"; }


 

   private void deleteFile(String oldPath) {  //删除文件
      // TODO Auto-generated method stub
      File oldFile = new File(oldPath);
      if(oldFile.isFile() && oldFile.exists()){
        oldFile.delete();
      }
    }

 

 

 

简单的上传文件

原文:http://www.cnblogs.com/fengbing9891/p/5307789.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!