你們好開通了獨立博客http://www.zhougou.net/ css
但願你們多多關注 html
本文對應鏈接:http://www.zhougou.net/archives/158java
2
過濾訪問的jsp時,會改變reqeust的類型,由HttpServletRequest變成MultiPartRequestWrapper,因此在kindeditor原始的jsp接收上傳的request的數據時,取得不了上傳的數據內容。
修改以後的upload_json.jsp文件源碼:
web
- <%@ page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%>
- <%@ page import="java.util.*,java.io.*"%>
- <%@ page import="java.text.SimpleDateFormat"%>
- <%@ page import="org.apache.commons.fileupload.*"%>
- <%@ page import="org.apache.commons.fileupload.disk.*"%>
- <%@ page import="org.apache.commons.fileupload.servlet.*"%>
- <%@ page import="org.json.simple.*"%>
- <%@ page
- import="org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper"%>
- <%
- //文件保存目錄路徑 //D:\Tomcat6.0\webapps\zswz\attached/
- String savePath = request.getSession().getServletContext()
- .getRealPath("/")
- + "photo/upload/";
- //文件保存目錄URL /zswz/attached/
- String saveUrl = request.getContextPath() + "/photo/upload/";
- //定義容許上傳的文件擴展名
- //定義容許上傳的文件擴展名
- HashMap<String, String> extMap = new HashMap<String, String>();
- extMap.put("p_w_picpath", "gif,jpg,jpeg,png,bmp");
- extMap.put("flash", "swf,flv");
- extMap.put("media",
- "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
- extMap.put("file",
- "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2"); //容許最大上傳文件大小 struts.xml struts.multipart.maxSize=3G
- long maxSize = 3000000000l;
- response.setContentType("text/html; charset=UTF-8");
- if (!ServletFileUpload.isMultipartContent(request)) {
- out.println(getError("請選擇文件。"));
- return;
- }
- //檢查目錄
- File uploadDir = new File(savePath);
- if (!uploadDir.isDirectory()) {
- out.println(getError("上傳目錄不存在。"));
- return;
- }
- //System.out.println("檢查目錄寫權限");
- //檢查目錄寫權限
- if (!uploadDir.canWrite()) {
- out.println(getError("上傳目錄沒有寫權限。"));
- return;
- }
- String dirName = request.getParameter("dir");
- //p_w_picpath
- if (dirName == null) {
- dirName = "p_w_picpath";
- }
- if (!extMap.containsKey(dirName)) {
- out.println(getError("目錄名不正確。"));
- return;
- }
- //建立文件夾
- savePath += dirName + "/";//D:\Tomcat6.0\webapps\zswz\attached/p_w_picpath/
- saveUrl += dirName + "/";///zswz/attached/p_w_picpath/
- File saveDirFile = new File(savePath);
- if (!saveDirFile.exists()) {
- saveDirFile.mkdirs();
- }
- SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
- String ymd = sdf.format(new Date());
- savePath += ymd + "/";//D:\Tomcat6.0\webapps\zswz\attached/p_w_picpath/20111129/
- saveUrl += ymd + "/";///zswz/attached/p_w_picpath/20111129/
- File dirFile = new File(savePath);
- if (!dirFile.exists()) {
- dirFile.mkdirs();
- }
- if (!dirFile.isDirectory()) {
- out.println(getError("上傳目錄不存在 。"));
- return;
- }
- //檢查目錄寫入權限
- if (!dirFile.canWrite()) {
- out.println(getError("上傳目錄沒有寫入權限。"));
- return;
- }
- //Struts2 請求 包裝過濾器,此處使用struts2的包裝過濾器
- MultiPartRequestWrapper wrapper = (MultiPartRequestWrapper) request;
- //得到上傳的文件名
- String fileName = wrapper.getFileNames("imgFile")[0];
- //imgFile
- //得到文件過濾器
- File file = wrapper.getFiles("imgFile")[0];
- //檢查擴展名
- String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1)
- .toLowerCase();
- if (!Arrays.<String> asList(extMap.get(dirName).split(","))
- .contains(fileExt)) {
- out.println(getError("上傳文件擴展名是不容許的擴展名。\n只容許"
- + extMap.get(dirName) + "格式。"));
- return;
- }
- //檢查文件大小
- if (file.length() > maxSize)
- {
- out.println(getError("上傳文件大小超過限制。"));
- return;
- }
- //重構上傳圖片的名稱
- SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
- String newImgName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;byte[] buffer = new byte[1024];
- //獲取文件輸出流
- FileOutputStream fos = new FileOutputStream(savePath +"/" + newImgName);
- //獲取內存中當前文件輸入流
- InputStream in = new FileInputStream(file);
- try {
- int num = 0;
- while ((num = in.read(buffer)) > 0)
- {
- fos.write(buffer, 0, num); }}
- catch (Exception e) {
- e.printStackTrace(System.err);}
- finally {
- in.close();
- fos.close();}
- //發送給 KE
- JSONObject obj = new JSONObject();
- obj.put("error", 0);
- obj.put("url", saveUrl +"/" + newImgName);
- ///zswz/attached/p_w_picpath/20111129/ p_w_picpath 20111129195421_593.jpg
- out.println(obj.toJSONString());
- //System.out.println("檢查目錄寫權限2");
- %>
- <%!
- private String getError (String message )
- {
- JSONObject obj = new JSONObject();
- obj.put("error", 1);
- obj.put("message", message);
- return obj.toJSONString();
- }%>
在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報服務器錯誤。
爲何取不到值,
是由於:
struts
2
過濾訪問的jsp時,會改變reqeust的類型,由HttpServletRequest變成MultiPartRequestWrapper,因此parseRequest就返回了null。
既然在過濾的時候改變reqeust的類型,那就能夠修改web.xml不過濾jsp。可是若是在jsp中用到了struts
2
的標籤就會報
500
的錯誤,這個方案在個人應用中不適用。
最終解決方案是,寫個Servlet來代替upload_json.jsp的功能。upload_json.jsp裏面的代碼大部分均可以複製到Servlet中, upload_json.jsp中的out.prinln返回值用 resp.getWriter().println()代替就行。