简单的上传文件

前端代码:

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

 
原文地址:https://www.cnblogs.com/fengbing9891/p/5307789.html