Kindeditor編輯器 jsp上傳錯誤解決方法 與struts2衝突整合

 

你們好開通了獨立博客http://www.zhougou.net/ css

但願你們多多關注 html

本文對應鏈接:http://www.zhougou.net/archives/158java

 

 

upload_json.jsp文件,關鍵在於struts2對於struts2過濾訪問的jsp時,會改變reqeust的類型,由HttpServletRequest變成MultiPartRequestWrapper,因此在kindeditor原始的jsp接收上傳的request的數據時,取得不了上傳的數據內容。

修改以後的upload_json.jsp文件源碼:web

 

  
  
  
  
  1. <%@ page language="java" contentType="text/html;charset=UTF-8"  pageEncoding="UTF-8"%> 
  2. <%@ page import="java.util.*,java.io.*"%> 
  3. <%@ page import="java.text.SimpleDateFormat"%> 
  4. <%@ page import="org.apache.commons.fileupload.*"%> 
  5. <%@ page import="org.apache.commons.fileupload.disk.*"%> 
  6. <%@ page import="org.apache.commons.fileupload.servlet.*"%> 
  7. <%@ page import="org.json.simple.*"%> 
  8. <%@ page  
  9.     import="org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper"%> 
  10. <%  
  11.     //文件保存目錄路徑    //D:\Tomcat6.0\webapps\zswz\attached/  
  12.     String savePath = request.getSession().getServletContext()  
  13.             .getRealPath("/")  
  14.             + "photo/upload/";  
  15.     //文件保存目錄URL /zswz/attached/  
  16.     String saveUrl = request.getContextPath() + "/photo/upload/";  
  17.     //定義容許上傳的文件擴展名  
  18.     //定義容許上傳的文件擴展名  
  19.     HashMap<String, String> extMap = new HashMap<String, String>();  
  20.     extMap.put("p_w_picpath", "gif,jpg,jpeg,png,bmp");  
  21.     extMap.put("flash", "swf,flv");  
  22.     extMap.put("media",  
  23.             "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");  
  24.     extMap.put("file",  
  25.             "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2"); //容許最大上傳文件大小 struts.xml struts.multipart.maxSize=3G 
  26.     long maxSize = 3000000000l;  
  27.     response.setContentType("text/html; charset=UTF-8");  
  28.     if (!ServletFileUpload.isMultipartContent(request)) {  
  29.         out.println(getError("請選擇文件。"));  
  30.         return;  
  31.     }  
  32.     //檢查目錄  
  33.     File uploadDir = new File(savePath);  
  34.     if (!uploadDir.isDirectory()) {  
  35.         out.println(getError("上傳目錄不存在。"));  
  36.         return;  
  37.     }  
  38.     //System.out.println("檢查目錄寫權限");  
  39.     //檢查目錄寫權限  
  40.     if (!uploadDir.canWrite()) {  
  41.         out.println(getError("上傳目錄沒有寫權限。"));  
  42.         return;  
  43.     }  
  44.     String dirName = request.getParameter("dir");  
  45.     //p_w_picpath  
  46.     if (dirName == null) {  
  47.         dirName = "p_w_picpath";  
  48.     }  
  49.     if (!extMap.containsKey(dirName)) {  
  50.         out.println(getError("目錄名不正確。"));  
  51.         return;  
  52.     }  
  53.     //建立文件夾  
  54.     savePath += dirName + "/";//D:\Tomcat6.0\webapps\zswz\attached/p_w_picpath/  
  55.     saveUrl += dirName + "/";///zswz/attached/p_w_picpath/  
  56.     File saveDirFile = new File(savePath);  
  57.     if (!saveDirFile.exists()) {  
  58.         saveDirFile.mkdirs();  
  59.     }  
  60.     SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");  
  61.     String ymd = sdf.format(new Date());  
  62.     savePath += ymd + "/";//D:\Tomcat6.0\webapps\zswz\attached/p_w_picpath/20111129/  
  63.     saveUrl += ymd + "/";///zswz/attached/p_w_picpath/20111129/  
  64.     File dirFile = new File(savePath);  
  65.     if (!dirFile.exists()) {  
  66.         dirFile.mkdirs();  
  67.     }  
  68.     if (!dirFile.isDirectory()) {  
  69.         out.println(getError("上傳目錄不存在 。"));  
  70.         return;  
  71.     }  
  72.     //檢查目錄寫入權限  
  73.     if (!dirFile.canWrite()) {  
  74.         out.println(getError("上傳目錄沒有寫入權限。"));  
  75.         return;  
  76.     }  
  77.     //Struts2 請求 包裝過濾器,此處使用struts2的包裝過濾器  
  78.     MultiPartRequestWrapper wrapper = (MultiPartRequestWrapper) request;  
  79.     //得到上傳的文件名  
  80.     String fileName = wrapper.getFileNames("imgFile")[0];  
  81.     //imgFile
  82.     //得到文件過濾器  
  83.     File file = wrapper.getFiles("imgFile")[0];  
  84.     //檢查擴展名  
  85.     String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1)  
  86.             .toLowerCase();  
  87.     if (!Arrays.<String> asList(extMap.get(dirName).split(","))  
  88.             .contains(fileExt)) {  
  89.         out.println(getError("上傳文件擴展名是不容許的擴展名。\n只容許"  
  90.                 + extMap.get(dirName) + "格式。"));  
  91.         return;  
  92.     }  
  93.     //檢查文件大小  
  94.     if (file.length() > maxSize)  
  95.      {        
  96.        out.println(getError("上傳文件大小超過限制。"));       
  97.           return;  
  98.           }     
  99.           //重構上傳圖片的名稱   
  100.           SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");  
  101.           String newImgName = df.format(new Date()) + "_"  + new Random().nextInt(1000) + "." + fileExt;byte[] buffer = new byte[1024];  
  102.           //獲取文件輸出流  
  103.           FileOutputStream fos = new FileOutputStream(savePath +"/" + newImgName);  
  104.           //獲取內存中當前文件輸入流  
  105.           InputStream in = new FileInputStream(file);  
  106.           try {        
  107.             int num = 0;      
  108.                 while ((num = in.read(buffer)) > 0)   
  109.                 {              
  110.                     fos.write(buffer, 0, num);        }}   
  111.                     catch (Exception e) {   
  112.                            e.printStackTrace(System.err);}   
  113.                            finally {       
  114.                               in.close();     
  115.                                    fos.close();}  
  116.                                    //發送給 KE  
  117.                                     JSONObject obj = new JSONObject();  
  118.                                     obj.put("error", 0);  
  119.                                     obj.put("url", saveUrl +"/" + newImgName);  
  120.                                     ///zswz/attached/p_w_picpath/20111129/  p_w_picpath 20111129195421_593.jpg  
  121.                                     out.println(obj.toJSONString());  
  122.                                         //System.out.println("檢查目錄寫權限2");  
  123. %> 
  124. <%!  
  125. private String getError (String message )  
  126.  {  
  127.         JSONObject obj = new JSONObject();  
  128.         obj.put("error", 1);  
  129.         obj.put("message", message);  
  130.         return obj.toJSONString();  
  131.     }%> 
在Common- FileUpload中,它把從客戶端提交過來的表單封裝成一個個FileItem對象,這也是它實現文件上傳功能 的核心類。另外一個很重要的類就是FileUploadBase,他的功能就是解析請求(request),如進行上傳文 件大小驗證,請求類型驗證(文件上傳的enctype要設置成multipart/form-data)等。咱們常常用到它 的子類ServletFileUpload。在FileUploadBase解析 request的過程當中會將文件保存到內存,若是文件大 小大於咱們設置的緩存的大小,它將把文件的其餘內容保存到一個臨時目錄,當咱們對FileItem 對象實 現正真上傳時會從內存區或臨時目錄將文件保存到正真的上傳目錄。
 
在kindeditor上傳圖片調試過程當中,發現
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
List items = upload.parseRequest(request);
Iterator itr = items.iterator();
while (itr.hasNext()) {
發現代碼4,items爲空,取不到須要上傳的文件,故沒有執行while循環,也就沒有返回值,kindeditor報服務器錯誤。
 
爲何取不到值,
是由於:struts2過濾訪問的jsp時,會改變reqeust的類型,由HttpServletRequest變成MultiPartRequestWrapper,因此parseRequest就返回了null。
 
既然在過濾的時候改變reqeust的類型,那就能夠修改web.xml不過濾jsp。可是若是在jsp中用到了struts2的標籤就會報500的錯誤,這個方案在個人應用中不適用。
 
最終解決方案是,寫個Servlet來代替upload_json.jsp的功能。upload_json.jsp裏面的代碼大部分均可以複製到Servlet中, upload_json.jsp中的out.prinln返回值用 resp.getWriter().println()代替就行。
相關文章
相關標籤/搜索