這是根據自己寫的一個教師管理系統實現的
由於主要用在頭像上,把上傳的頭像存儲到本地
為了方便,設置一個虛擬地址:
然后添加虛擬路徑和實際路徑即可
前台:
<div class="pic" style="opacity: 1"> <a id="apic" href="/teacherImage/${sessionScope.teacher.tpic}"><img alt="教師照片" style="opacity: 1" width=90px height=90px id="pic" src="/teacherImage/${sessionScope.teacher.tpic}"/></a> </div> <div class="tlbl"> <form id="picUpload" method="post" enctype="multipart/form-data"> <input type="file" name="picUploadFile" onchange="uploadPic()"/> </form> </div>
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; }
主要實現方法就是上邊,如若需要其他需求,可按上邊進行更改