1. 程式人生 > >圖片的上傳(多張圖片的上傳)

圖片的上傳(多張圖片的上傳)

頁面展示:點選連結檢視圖片(用到了jstl外掛)

jsp頁面:
<LINK href="${basePath}plugins/uploadify/uploadify.css" type="text/css" rel="stylesheet" />
<script language="javascript" type="text/javascript">
    //防止客戶端快取檔案,造成uploadify.js不更新,而引起的“喔唷,崩潰啦”  
    document.write ("<script type='text/javascript' " + "
src='${basePath}plugins/uploadify/jquery.uploadify.min.js?" + new Date () + "'><\/script>"); </script> <style> .uploadify-box { width: 130px; margin: 0px; margin-top: 10px; } <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <%@taglib prefix="f" uri="
http://java.sun.com/jsp/jstl/fmt"%> <%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%> <script type="text/javascript"> $(function() { //圖片上傳 $('.uploadImage').each(function(){ var id= $(this).attr("id"); var $this = $(this); $("#"+id).uploadify({ fileSizeLimit :
'1024KB', uploader : '${basePath}/core/upload!uploadImage.action', // 伺服器端處理地址 swf : '${basePath}js/uploadify/uploadify.swf', // 上傳使用的 Flash buttonText : "上傳圖片", buttonCursor : 'hand', fileObjName : 'uploadify',// 上傳引數名稱 後臺action裡面的屬性uploadify fileTypeExts : "*.jpg;*.png;*.gif", // 副檔名 fileTypeDesc : "請選擇 jpg png gif 檔案", removeTimeout : 1, // 檔案說明 auto : true, // 選擇之後,自動開始上傳 multi : true, // 是否支援同時上傳多個檔案 queueSizeLimit : 10, // 允許多檔案上傳的時候,同時上傳檔案的個數 queueID : 'show_queueID', onUploadSuccess : function(file,data, response) { var data = jQuery.parseJSON(data); if(data.error == 1){ ldDialog.alert(data.message); }else{ //地址賦值 var fname=data.fileName; var pth=data.url; var ul=$("#workSecurityCheck\\.checkPhoto").val(); $("#workSecurityCheck\\.checkPhoto").val(ul+fname+";"+pth+"|"); //圖片顯示 var htmlString ="<a target='_blank' href='${basePath}/"+data.url+"' style='color: #ff7800;padding-right:20px;'>"+fname+"</a>"; $("#workSecurityCheck\\.checkPhoto").after(htmlString); } } }); }); }); </script> <tr> <td width="20%" class="right yhItem1"> <span class="font12">*</span>照片: </td> <td> <c:if test="${readOnly == null }"> <input type="button" id="uploadImage" class="uploadImage" name="button" ${readOnly} value="上傳圖片"/> </c:if> </td> </tr> <tr> <td width="20%" class="right yhItem1"></td> <td> <div id="deleteID"> <c:if test="${not empty workSecurityCheck.checkPhoto}"> <c:forEach items="${fn:split(workSecurityCheck.checkPhoto,'|')}" var="val" > <a target='_blank' href="${basePath}/${fn:substring(val, fn:indexOf(val, ';')+1 , fn:length(val))}" style="color: #ff7800;padding-right:20px;">${fn:substring(val, 0, fn:indexOf(val, ';') )}</a> </c:forEach> </c:if> </div> <input name="workSecurityCheck.checkPhoto" type="hidden" class="input138 ldText" id="workSecurityCheck.checkPhoto" value="${workSecurityCheck.checkPhoto}" /> </td> </tr> java : @RequestMapping("core/upload!uploadImage.action") public void uploadImage(@RequestParam(value = "uploadify", required = false) MultipartFile uploadify,HttpServletResponse response,ModelMap modelMap)throws Exception { String savePath = getRequest().getServletContext().getRealPath("/")+ "/" + "upload/"; String saveUrl = "upload/"; HashMap<String, String> extMap = new HashMap<String, String>(); extMap.put("image", "gif,jpg,jpeg,png,bmp"); extMap.put("csv", "csv"); //獲取系統定義的上傳最大限值 Integer uploadMaxSize =Integer.valueOf(optionService.getByOptionName(CoreValue.OPTION_UPLOAD_MAX_SIZE).getOptionValue()); long maxSize = Long.valueOf(String.valueOf(uploadMaxSize)).longValue(); String maxSizeKb = StringUtil.formatNumber(new Double(maxSize / 1024L),"0"); response.setContentType("text/html; charset=UTF-8"); String jsonString =""; if (uploadify==null || uploadify.isEmpty()) { jsonString = getError("請選擇檔案。"); response.getWriter().println(jsonString); return; } File uploadDir = new File(savePath); if (!uploadDir.isDirectory()) { jsonString = getError(savePath + "上傳目錄不存在。"); response.getWriter().println(jsonString); return; } if (!uploadDir.canWrite()) { jsonString = getError("上傳目錄沒有寫許可權。"); response.getWriter().println(jsonString); return; } String dirName = getRequest().getParameter("dir"); if (dirName == null) { dirName = "image"; } if (!extMap.containsKey(dirName)) { jsonString = getError("目錄名不正確。"); response.getWriter().println(jsonString); return; } savePath = savePath + dirName + "/"; saveUrl = saveUrl + dirName + "/"; File saveDirFile = new File(savePath); if (!saveDirFile.exists()) { saveDirFile.mkdirs(); } SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd"); String ymd = sdf.format(new Date()); savePath = savePath + ymd + "/"; saveUrl = saveUrl + ymd + "/"; File dirFile = new File(savePath); if (!dirFile.exists()) { dirFile.mkdirs(); } String fileName = uploadify.getOriginalFilename(); long fileSize = uploadify.getSize(); if (fileSize > maxSize) { jsonString = getError("上傳檔案大小超過限制。最大為" + maxSizeKb + "kb"); response.getWriter().println(jsonString); return; } String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase(); if (!Arrays.asList(((String) extMap.get(dirName)).split(",")).contains(fileExt)) { jsonString = getError("不允許的上傳檔案型別。"); response.getWriter().println(jsonString); return; } SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); String newFileName = df.format(new Date()) + "_"+ new Random().nextInt(1000) + "." + fileExt; File uploadedFile = null; try { uploadedFile = new File(savePath, newFileName); if(uploadedFile.exists()){ } if(!uploadedFile.exists()){ uploadedFile.mkdirs(); } uploadify.transferTo(uploadedFile); } catch (Exception e) { jsonString = getError("上傳檔案失敗。"); response.getWriter().println(jsonString); return; } JSONObject obj = new JSONObject(); obj.put("error", Integer.valueOf(0)); obj.put("url", saveUrl + newFileName); obj.put("fileName", fileName); jsonString = obj.toJSONString(); modelMap.put("fileName", fileName); modelMap.put("newFileName", newFileName); modelMap.put("url", saveUrl + newFileName); response.getWriter().println(jsonString); return; }