一、前端頁面前端
<div class="tkDiv" id="addLOGO" style="display:none;z-index:12;width:800px;height:auto;margin-left:-400px;margin-top: -160px"> <div class="tk1_header" style="width:800px;height:40px;line-height:40px;background: #263552 !important;color: #ffffff !important;margin-left:-10px;margin-top:-10px;"> <span style="font-size: 16px;margin-left:20px;color:#FFF" id="gn_title">添加主頁圖片</span> <a id="close_modal" style="width:30px;height:20px;background-size:20px;float: right;">×</a> </div> <div class="tk1" id="addZ" style="width:750px;height:200px;"> <div class="tk1_content" id="registerDiv" style="width:750px;"> <form id="imageForm" class="bs-docs-example form-horizontal" method="post" action="<%=path %>/webCenter.do" enctype="multipart/form-data"> <input type="hidden" name="method" value="saveConferencesImage"> <input type="hidden" id="imageId" name="imageId" value="-1"> <table style="width:750px"> <tr height="50px"> <td align="right" width="150px" > 圖片名稱 </td> <td> <input id="imageName" class="form-control" name="imageName" type="text" style="margin-left:40px;display:inline-block;height:34px;"/> </td> </tr> <tr height="50px"> <td align="right" width="150px" > 上傳圖片 </td> <td> <input id="imageFile" name="imageFile" type="file" style="margin-left:40px;display:inline-block;height:34px;"/> </td> </tr> </table> </form> </div> <div style="border-top: 1px solid rgba(0, 0, 0, 0.1);text-align: center;"> <input id="saveBtn" type="button" class="button" value="添 加" style="border-radius:0;width:260px;height:40px;margin:auto 50px;margin:20px; background: #263552 !important;color: #ffffff !important;"/> </div> </div>
二、js代碼java
$(function(){ $("#saveBtn").click(function(){ var imageName = $("#imageName").val(); var imageFile = $("#imageFile").val(); if(imageName == '' || imageName.length == 0){ alert("請輸入圖片名稱"); return; }if(imageFile == '' || imageFile.length == 0){ alert("請選擇要上傳的圖片"); return; } var formData = new FormData(); formData.append("imagePath", $("#imageFile")[0].files[0]); $.ajax({ url:"<%=path%>/webCenter.do?uploadConImage", type:"post", data:formData, dataType:"json", // 告訴jQuery不要去處理髮送的數據 processData: false, // 告訴jQuery不要去設置Content-Type請求頭 contentType: false, beforeSend: function () { console.log("正在進行,請稍候"); }, success:function(data){ if(data.state == 0){ alert(data.msg) }else{ $("#imageForm").submit(); } } }) }) })
三、後臺數據處理web
① 第一步驗證圖片大小ajax
//判斷圖片大小,不是這個大小的提示不能上傳 @RequestMapping(params = "uploadConImage",method = RequestMethod.POST) public void uploadConImage(HttpServletRequest request,HttpServletResponse response){ try{ MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request; MultipartFile mFile = mRequest.getFile("imagePath"); InputStream is = mFile.getInputStream();//輸入流 BufferedImage bufferedImg = ImageIO.read(is); int width = bufferedImg.getWidth();//獲取圖片寬高 int height = bufferedImg.getHeight(); JSONObject json = new JSONObject(); if(width != 500 && height != 300){ float bili = (float)(new Float(height)/new Float(width)); float b = (float)(Math.round(bili*100))/100; if(b != new Float(0.45)){ json.accumulate("state", 0); json.accumulate("msg", "請上傳分辨率爲500*300的圖片或者長寬比爲0.6的圖片(高除以寬爲0.6)"); }else{ json.accumulate("state", 1); } }else{ json.accumulate("state", 1); } writeJson(response, json.toString()); } catch (Exception e) { e.printStackTrace(); } }
② 在js裏面用$("#imageForm").submit();提交form表單,上傳圖片。注意:用form表單上傳圖片時,在from表單上要添加 enctype="multipart/form-data" 屬性。form表單看上面代碼,下面是後臺數據處理。json
@RequestMapping(params = "method=saveConferencesImage",method = RequestMethod.POST) public void saveConferencesImage(int imageId,String imageName,HttpServletRequest request,HttpServletResponse response){ try { HttpSession session = this.getSession(request); Adminuser adminUser = session.getAttribute("centerAdminUser") == null?null:(Adminuser) session.getAttribute("centerAdminUser"); if(adminUser == null){ try { response.sendRedirect(request.getContextPath()+"/center/index.jsp"); } catch (Exception e) { e.printStackTrace(); } }else{ String conId = request.getSession().getAttribute("conId") == null ? null: request.getSession().getAttribute("conId").toString(); if (conId == null) { response.sendRedirect(request.getContextPath()+"/center/index.jsp"); } Conferences conferences = webService.getConferencesById(Integer.parseInt(conId)); ConferencesImage conferencesImage = null; if(imageId == -1){ conferencesImage = new ConferencesImage(); }else{ conferencesImage = webService.getConferencesImageById(imageId); } conferencesImage.setConferencesId(Integer.parseInt(conId)); conferencesImage.setImageName(imageName); int level = webService.getConferencesImageLevel(Integer.parseInt(conId)); conferencesImage.setLevel(level); MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest)request; MultipartFile mFile = mRequest.getFile("imageFile"); String fileName= mFile.getOriginalFilename();//獲取文件名 fileName = fileName.substring(fileName.lastIndexOf("."),fileName.length()); String newFileName = String.valueOf(System.currentTimeMillis())+"_mainPage"+fileName; String filePath = request.getSession().getServletContext().getRealPath("/"); filePath = filePath + conferences.getAbbreviation()+"/images/mainPage/"; File file = new File(filePath); if(!file.exists()){ file.mkdirs(); } File saveFile = new File(filePath+newFileName); mFile.transferTo(saveFile); conferencesImage.setImageUrl("/"+conferences.getAbbreviation()+"/images/mainPage/"+newFileName); webService.saveObject(conferencesImage); response.sendRedirect(request.getContextPath()+"/webCenter.do?getConferencesImage"); } } catch (Exception e) { e.printStackTrace(); } }