这是根据自己写的一个教师管理系统实现的
由于主要用在头像上,把上传的头像存储到本地
为了方便,设置一个虚拟地址:
然后添加虚拟路径和实际路径即可
前台:
js代码:
function uploadPic(){ var formData = new FormData($('#picUpload')[0]); $.ajax({ type: 'post', url: "teacher/uploadPic.action", data: formData, cache: false, processData: false, contentType: false, }).success(function (data) { if(data !== $("#apic").attr("href")){ $("#apic").attr("href",data); $("#pic").attr("src",data); alert("头像上传成功!"); } else{ alert("图片上传失败!"); } }).error(function () { alert("上传失败"); }); }
后台:
@RequestMapping(value="/teacher/uploadPic", produces=MediaType.TEXT_PLAIN_VALUE+";charset=utf-8") @ResponseBody public String uploadFile(MultipartFile picUploadFile,HttpServletRequest request) throws Exception{ //获取原头像地址 Teacher teacher = (Teacher) request.getSession().getAttribute("teacher"); String pic = teacher.getTpic(); //判断文件是否为图片 String originalFileName = picUploadFile.getOriginalFilename(); String houzhui = originalFileName.substring(originalFileName.lastIndexOf(".")); if(!houzhui.equals(".jpg")&&!houzhui.equals(".png")) { return "/teacherImage/"+pic; } //上传文件 String newFileName = UUID.randomUUID()+houzhui; File newFile = new File(picUrl,newFileName); picUploadFile.transferTo(newFile); //删除原有头像文件 String oldPicUrl = picUrl + "/" + pic; File picFile = new File(oldPicUrl); if(picFile.exists()) { picFile.delete(); } //把现有文件地址保存 teacher.setTpic(newFileName); request.getSession().removeAttribute("teacher"); request.getSession().setAttribute("teacher",teacher); teacherService.updateTeacher(teacher); return "/teacherImage/"+newFileName; }
主要实现方法就是上边,如若需要其他需求,可按上边进行更改