照片上傳預覽並儲存的功能
一、現在jsp中定義一個上傳檔案的form表單
<form id="imgForm" action="" method="post" enctype="multipart/form-data"> <p class="upload clearfix">
<!-- 其中 真正的上傳input隱藏在了上傳照片的下面,這樣可以給上傳按鈕自定義樣式,大小與外層樣式一致 --> <input type="file" name="picFile" id="imgUrl" onchange="changepic(this)"
style="overflow: hidden;position: absolute;left: 75px;margin-top: 20px;float: left;width: 74px;height: 74px;"> <a href="###" id="showFile" style="position: relative;"><i></i><span>上傳照片</span></a> <b><img id="img" src=""></b> <!-- 展示上傳之後的圖片 --> </p>
<!--傳遞手機號,作為該使用者存放照片的資料夾 --> <input name="imgMobile" type="hidden" value="<%=mobile1%>" id="imgMobile">
<!-- 傳遞自定義照片的名稱(不重複) --> <input name="imgName" type="hidden" value="" id="imgName"> </form>
二、在js當上傳圖片後非同步提交表單
//捕獲上傳檔案狀態 function changepic(){
//ie9及以下不相容這個fileReader(); var reads= new FileReader(); file = document.getElementById('imgUrl').files[0]; reads.readAsDataURL(file); reads.onload=function (e) { var fileName = $("#imgUrl").val(); var fileType = fileName.substring(fileName.lastIndexOf(".")+1); if(fileType=="jpg" || fileType=="JPG" || fileType=="jpeg" || fileType=="JPEG" || fileType=="png" || fileType=="PNG"){ var filename = 'thjdpx' + (Math.random()+'').substr(2) + "." + fileType; //動態生成圖片的名字,用於後期存到資料庫中 $("#imgName").val(filename); var formData = new FormData(document.getElementById("imgForm")); //使用ajax非同步提交表單的時候的引數data要設定成formData,要按照這樣寫,否則後臺接收不到上傳的檔案
$.ajax({ type : "POST", url : "/patch/thjdpx/action/thjdpxPeOfflineTraineeInfo_saveOfflineTraineeImg.action", //呼叫儲存圖片的方法 data: formData, async: false, cache: false, contentType: false, processData: false, dataType : 'json', error: function(request) { $("#message").html("照片上傳失敗。"); $("#eject").show(); }, success: function(data) { //data = eval("(" + data + ")"); if(data.success == "true"){ $("#img").attr('src',data.imgPath); $("#imgUrl1").val(data.imgPath); }else{ $("#img").attr('src',data.imgPath); $("#imgUrl1").val(data.imgPath); $("#message").html("照片上傳失敗。"); $("#eject").show(); } } }) }else{ $("#message").html("請上傳jpg、png、jpeg格式的檔案。"); $("#eject").show(); } }; }
三、java程式碼中的寫法,上傳圖片的方法
/** * 上傳照片的方法 * 返回圖片在伺服器中的路徑和上傳狀態 */ public String saveOfflineTraineeImg(){ HttpServletRequest request = ServletActionContext.getRequest(); Map<String, String> map = new HashMap<String, String>(); String imgMobile = request.getParameter("imgMobile"); //獲取表單中的手機號 String imgName = request.getParameter("imgName");
//定義伺服器中存放圖片的資料夾路徑,為減少一個資料夾的承載能力,這個給每個學員建立了一個自己的資料夾,圖片上傳到自己所在的資料夾中。 String filePath = "/incoming/export/" + imgMobile ; String realPath = ServletActionContext.getServletContext().getRealPath(filePath); String imgPath = ""; map.put("success", "false"); map.put("message", "上傳失敗。"); //檔案上傳使用的元件,先建立一個工廠然後獲取 DiskFileItemFactory factory = new DiskFileItemFactory();
// 負責處理上傳的檔案資料,並將表單中每個輸入項封裝成一個FileItem 物件中 ServletFileUpload upload = new ServletFileUpload(factory); if(StringUtils.isNotBlank(imgMobile)){ try { request.setCharacterEncoding("UTF-8"); //設定編碼格式 List<FileItem> items = upload.parseRequest(request); //將表單的每個輸入項存放到list表單中 Iterator<FileItem> itr = items.iterator(); while (itr.hasNext()) { //循序表單傳入的檔案 FileItem item = (FileItem) itr.next(); //檢視該學員的圖片資料夾是否存在,不存在則建立此資料夾 File realFile = new File(realPath); if (!realFile .exists() && !realFile .isDirectory()) { realFile.mkdirs(); //建立資料夾 ,多級目錄一同建立 } if (!item.isFormField()) { //如果檔案不為空 if(item.getName() !=null && !item.getName().equals("")) { File tempFile = new File(item.getName());//獲取上傳的檔案 File file = new File(realPath,imgName);//新建一個檔案 try { item.write(file);//將原檔案寫入新檔案中 imgPath = filePath + "/" + imgName; //返回圖片路徑到jsp中,方便後期儲存到資料庫的操作 map.put("imgPath", imgPath); map.put("success", "true"); map.put("message", "上傳成功。"); } catch (Exception e) { e.printStackTrace(); } } } } } catch ( FileUploadException | UnsupportedEncodingException e1) { e1.printStackTrace(); } } this.setJsonString(JsonUtil.toJSONString(map)); return "json"; }