import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.Random; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItemFactory; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.struts2.ServletActionContext; import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper; import org.json.simple.JSONObject; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; public class ImgUploadAction extends ActionSupport { private static final long serialVersionUID = 1L; public String imgUpload() { //獲取response、request對象 ActionContext ac = ActionContext.getContext(); HttpServletResponse response = (HttpServletResponse) ac.get(ServletActionContext.HTTP_RESPONSE); HttpServletRequest request = (HttpServletRequest) ac.get(ServletActionContext.HTTP_REQUEST); PrintWriter out = null; //輸出流 try { out = response.getWriter(); } catch (IOException e1) { e1.printStackTrace(); } String savePath = ServletActionContext.getServletContext().getRealPath("/") + "attached/"; // 文件保存目錄URL String saveUrl = request.getContextPath() + "/attached/"; // 定義容許上傳的文件擴展名 HashMap<String, String> extMap = new HashMap<String, String>(); extMap.put("image", "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"); // 最大文件大小 long maxSize = 1000000; response.setContentType("text/html; charset=UTF-8"); if (!ServletFileUpload.isMultipartContent(request)) { out.println(getError("請選擇文件。")); return null; } // 檢查目錄 File uploadDir = new File(savePath); if (!uploadDir.isDirectory()) { out.println(getError("上傳目錄不存在。")); return null; } // 檢查目錄寫權限 if (!uploadDir.canWrite()) { out.println(getError("上傳目錄沒有寫權限。")); return null; } String dirName = request.getParameter("dir"); if (dirName == null) { dirName = "image"; } if (!extMap.containsKey(dirName)) { out.println(getError("目錄名不正確。")); return null; } // 建立文件夾 savePath += dirName + "/"; saveUrl += dirName + "/"; File saveDirFile = new File(savePath); if (!saveDirFile.exists()) { saveDirFile.mkdirs(); } SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); String ymd = sdf.format(new Date()); savePath += ymd + "/"; saveUrl += ymd + "/"; File dirFile = new File(savePath); if (!dirFile.exists()) { dirFile.mkdirs(); } FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8"); MultiPartRequestWrapper wrapper = (MultiPartRequestWrapper) request; // 得到上傳的文件名 String fileName = wrapper.getFileNames("imgFile")[0];// imgFile,imgFile,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 null; } // 檢查文件大小 if (file.length() > maxSize) { out.println(getError("上傳文件大小超過限制。")); return null; } // 重構上傳圖片的名稱 SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); String newImgName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt; byte[] buffer = new byte[1024]; // 獲取文件輸出流 FileOutputStream fos; // 獲取內存中當前文件輸入流 InputStream in; try { fos = new FileOutputStream(savePath + "/" + newImgName); in = new FileInputStream(file); int num = 0; while ((num = in.read(buffer)) > 0) { fos.write(buffer, 0, num); } in.close(); fos.close(); } catch (FileNotFoundException e1) { e1.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // 發送給 kindeditor JSONObject obj = new JSONObject(); obj.put("error", 0); obj.put("url", saveUrl + "/" + newImgName); out.println(obj.toJSONString()); return null; } private String getError(String message) { JSONObject obj = new JSONObject(); obj.put("error", 1); obj.put("message", message); return obj.toJSONString(); } }
kindeditor有自帶的jsp圖片上傳demohtml
uploadJson : '../jsp/upload_json.jsp'java
但若是按照upload_json.jsp中的程序進行上傳時執行到apache
List items = upload.parseRequest(request); Iterator itr = items.iterator(); while (itr.hasNext()) {}
發現itr爲空 取不到上傳文件 故沒有執行while循環,也就沒有返回值,kindeditor報服務器錯誤.爲何取不到值,是由於:json
struts2過濾訪問jsp時,會改變reqeust的類型,由HttpServletRequest變成MultiPartRequestWrapper,因此parseRequest就返回了null服務器
因而咱們就須要對request進行轉換
app
MultiPartRequestWrapper wrapper = (MultiPartRequestWrapper) request;
這樣就能夠經過wrapper獲取上傳文件dom
String fileName = wrapper.getFileNames("imgFile")[0]; File file = wrapper.getFiles("imgFile")[0];