struts2 +kindeditor上传图片+管理图片
kindeditor struts 上传图片http://blog.csdn.net/alinaxz/article/details/6597516http://wsfly.iteye.com/blog/997791http://dsea.iteye.com/blog/1068863http://www.cnitblog.com/intrl/archive/2009/04/18/56447.htmlhttp://topic.csdn.net/u/20110625/14/bc104e1b-1af8-4adf-825e-a389edd837be.htmlhttp://topic.csdn.net/u/20090514/10/ba62c761-e591-4c9e-859a-87907634ea13.htmlhttp://topic.csdn.net/u/20090514/10/ba62c761-e591-4c9e-859a-87907634ea13.htmlhttp://www.iteye.com/http://www.iteye.com/news/23482struts2 + kindeditor上传图片时遇到的各种问题!!
《《《《《《《《《《《《《《《《 第一个问题》》》》》》》》》》》》》》》》》》》》》
直接部署kindeidtor在tomcat下可以正确的上传图片,当和struts2整合(就是想把原来写在jsp中的代码写在一个类中)到一块的时候上传不成功,debug时候在List items =upload.parseRequest(request);总体是items为空,奇怪的就是在jsp上就可以和struts2整合就不行,搞了半天终于找到方案:
-----------------------------------------------------------------------------------------------参考文章:http://auzll.iteye.com/blog/919981
一、项目基本环境:struts2等
二、基本需求&问题:需要自己写程序调用common-fileupload来处理上传的文件,但在代码调用upload.parseRequest(request)来处理时,返回了空的items
三、处理方法1、按照网上找到对该问题的相关处理方法: struts2@Controller@SuppressWarnings("unchecked")publicclass ImageManagerAction extendsActionSupport {
privatestatic finallong serialVersionUID =1L;privatestatic finalint UPLOAD_MSG_SUCCESS =0;privatestatic finalint UPLOAD_MSG_FAIL =1;
publicString uploadImage() throws Exception {Sys_useruser =getLoginUserInfo();HttpServletResponse response= ServletActionContext.getResponse();HttpServletRequest request= ServletActionContext.getRequest();response.setContentType("text/html; charset=UTF-8");PrintWriterout =response.getWriter();StringconfigPath =SystemConfig.getString("configPath");//文件保存目录路径(如:D:Program FilesTomcat6.0webappseditor")String savePath =StringUtils.isEmpty(configPath) ?ServletActionContext.getServletContext().getRealPath("/")+SystemConfig.getString("img_file_root")+ "/" :configPath;//文件保存目录URL("/editor")String saveUrl =SystemConfig.getString("saveUrl")+SystemConfig.getString("img_file_root") +"/";System.out.println(savePath + "," +saveUrl);
//定义允许上传的文件扩展名HashMap extMap = newHashMap();extMap.put("image",SystemConfig.getString("allow_file_img"));//最大文件大小long maxSize =Long.parseLong(SystemConfig.getString("maxSize"));
if (!ServletFileUpload.isMultipartContent(request)){returngetError("请选择文件。");}//检查目录File uploadDir = newFile(savePath);if(!upl oadDir.isDirectory()) {uploadDir.mkdirs();}//检查目录写权限if(!uploadDir.canWrite()) {returngetError("上传目录没有写权限。");}
StringuserName =user.getLoginId();if(StringUtils.isEmpty(userName)){returngetError("登录账号为空,无法找到对应的上传文件目录。");}//创建文件夹savePath += userName +"/";saveUrl += userName +"/";File saveDirFile = newFile(savePath);if(!saveDirFile.exists()) {saveDirFile.mkdirs();}FileItemFactory factory= new DiskFileItemFactory();ServletFileUploadupload = new ServletFileUpload(factory);upload.setHeaderEncoding("UTF-8");List items =upload.parseRequest(request);Iterator itr =items.iterator();while (itr.hasNext()){FileItem item =(FileItem) itr.next();String fileName =item.getName();if(!item.isFormField()) {//检查文件大小if (item.getSize() >maxSize) {returngetError("上传文件大小超过限制。");}//检查扩展名String fileExt =fileName.substring(fileName.lastIndexOf(".") +1).toLowerCase();if (!Arrays.asList(extMap.get("image").split(",")).contains(fileExt)){returngetError("上传文件扩展名是不允许的扩展名。n只允许"+ extMap.get("image") +"格式。");}
SimpleDateFormatdf = new SimpleDateFormat("yyyyMMddHHmmss");StringnewFileName =df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;try {FileuploadedFile =new File(savePath, newFileName);item.write(uploadedFile);} catch (Exception e) {returngetError("上传文件失败。");}
JSONObjectobj =new JSONObject();obj.put("error", UPLOAD_MSG_SUCCESS);obj.put("url", saveUrl + newFileName);System.out.println(obj.toJSONString() + "----------------");out.println(obj.toJSONString());}}returnnull;}
publicString managerImage() throws Exception {Sys_useruser =getLoginUserInfo();HttpServletResponse response= ServletActionContext.getResponse();HttpServletRequest request= ServletActionContext.getRequest();response.setContentType("text/html; charset=UTF-8");PrintWriterout =response.getWriter();StringconfigPath =SystemConfig.getString("configPath");//文件保存目录路径(如:D:Program FilesTomcat6.0webappseditor")String rootPath =StringUtils.isEmpty(configPath) ?ServletActionContext.getServletContext().getRealPath("/")+ "/" :configPath;String rootUrl =SystemConfig.getString("saveUrl") +SystemConfig.getString("img_file_root") +"/";//图片扩展名String[] fileTypes =new String[]{"gif", "jpg", "jpeg", "png","bmp"};
StringdirName =user.getLoginId();if (dirName != null) {rootPath+= dirName+ "/";rootUrl+= dirName+ "/";FilesaveDirFile =new File(rootPath);if (!saveDirFile.exists()) {saveDirFile.mkdirs();}}//根据path参数,设置各路径和URLString path =request.getParameter("path") != null ? request.getParameter("path"): "";String currentPath =rootPath + path;String currentUrl =rootUrl + path;String currentDirPath =path;String moveupDirPath ="";if (!"".equals(path)){String str =currentDirPath.substring(0, currentDirPath.length() -1);moveupDirPath =str.lastIndexOf("/") >= 0 ? str.substring(0,str.lastIndexOf("/") + 1) : "";}
//排序形式,name or size ortypeString order =request.getParameter("order") != null ?request.getParameter("order").toLowerCase() :"name";
//不允许使用..移动到上一级目录if (path.indexOf("..")>= 0) {out.println("Access isnot allowed.");returnnull;}//最后一个字符不是/if (!"".equals(path)&& !path.endsWith("/")) {out.println("Parameteris not valid.");returnnull;}//目录不存在或不是目录File currentPathFile =new File(currentPath);if(!currentPathFile.isDirectory()){out.println("Directorydoes not exist.");returnnull;}
//遍历目录取的文件信息List fileList = newArrayList();if(currentPathFile.listFiles() != null) {for (File file :currentPathFile.listFiles()) {Hashtable hash = newHashtable();String fileName =file.getName();if(file.isDirectory()){hash.put("is_dir",true);hash.put("has_file",(file.listFiles() != null));hash.put("filesize",0L);hash.put("is_photo",false);hash.put("filetype","");} elseif(file.isFile()){String fileExt =fileName.substring(fileName.lastIndexOf(".") +1).toLowerCase();hash.put("is_dir",false);hash.put("has_file",false);hash.put("filesize",file.length());hash.put("is_photo",Arrays.asList(fileTypes).contains(fileExt));hash.put("filetype",fileExt);}hash.put("filename",fileName);hash.put("datetime",new SimpleDateFormat("yyyy-MM-ddHH:mm:ss").format(file.lastModified()));fileList.add(hash);}}
if ("size".equals(order)) {Collections.sort(fileList, new SizeComparator());} else if ("type".equals(order)) {Collections.sort(fileList, new TypeComparator());} else {Collections.sort(fileList, new NameComparator());}JSONObjectresult =new JSONObject();result.put("moveup_dir_path",moveupDirPath);result.put("current_dir_path",currentDirPath);result.put("current_url", currentUrl);result.put("total_count", fileList.size());result.put("file_list", fileList);out.println(result.toJSONString());returnnull;}publicclass NameComparator implementsComparator {publicint compare(Object a, Object b) {HashtablehashA =(Hashtable)a;HashtablehashB =(Hashtable)b;if (((Boolean)hashA.get("is_dir")) && !((Boolean)hashB.get("is_dir"))) {return-1;} else if (!((Boolean)hashA.get("is_dir")) && ((Boolean)hashB.get("is_dir"))) {return1;} else {return((String)hashA.get("filename")).compareTo((String)hashB.get("filename"));}}}publicclass SizeComparator implementsComparator {publicint compare(Object a, Object b) {HashtablehashA =(Hashtable)a;HashtablehashB =(Hashtable)b;if (((Boolean)hashA.get("is_dir")) && !((Boolean)hashB.get("is_dir"))) {return-1;} else if (!((Boolean)hashA.get("is_dir")) && ((Boolean)hashB.get("is_dir"))) {return1;} else {if (((Long)hashA.get("filesize")) > ((Long)hashB.get("filesize"))) {return1;} else if (((Long)hashA.get("filesize")) <</span> ((Long)hashB.get("filesize"))) {return-1;} else {return0;}}}}publicclass TypeComparator implementsComparator {publicint compare(Object a, Object b) {HashtablehashA =(Hashtable)a;HashtablehashB =(Hashtable)b;if (((Boolean)hashA.get("is_dir")) && !((Boolean)hashB.get("is_dir"))) {return-1;} else if (!((Boolean)hashA.get("is_dir")) && ((Boolean)hashB.get("is_dir"))) {return1;} else {return((String)hashA.get("filetype")).compareTo((String)hashB.get("filetype"));}}}privateString getError(String message) throws IOException {JSONObjectobj =new JSONObject();obj.put("error", UPLOAD_MSG_FAIL);obj.put("message", message);ServletActionContext.getResponse().getWriter().println(obj.toJSONString());returnnull;}
privateSys_user getLoginUserInfo(){return(Sys_user) ActionContext.getContext().getSession().get("session_sys_user");}}#######################################################SystemConfig##########上传文件的大小maxSize =1000000#文件存放根目录img_file_root =notice#文件上传保存URL#saveUrl =http://221.179.128.178:8000/#saveUrl =http://221.179.128.173:9300/saveUrl =http://localhost:8080/#文件存放目录configPath =D:/home/ciss/noticeimg/#configPath=e:/excel/#允许上传文件格式allow_file_img =gif,jpg,jpeg,png,bmp#######################################################SystemConfig#########importjava.util.MissingResourceException;importjava.util.ResourceBundle;
publicclass SystemConfig {
privatestatic finalString BUNDLE_NAME = "SystemConfig";
privatestatic finalResourceBundle RESOURCE_BUNDLE =ResourceBundle.getBundle(BUNDLE_NAME);
privateSystemConfig(){}
publicstatic StringgetString(String key) {try {returnRESOURCE_BUNDLE.getString(key);} catch (MissingResourceException e) {return"no " +key +" key!";}}publicstatic voidmain(String[] args) {System.out.println(SystemConfig.getString("pwd.reset"));}}#######################################################SystemConfig#########
web.xml ==把此filter次序放到struts2的filter次序之前
uploadcom.huawei.ciss.common.web.UploadFilter
upload/ajaxImg_uploadImage.doupload/ajaxImg_managerImage.do
==filter
importjava.io.IOException;
importjavax.servlet.Filter;importjavax.servlet.FilterChain;importjavax.servlet.FilterConfig;importjavax.servlet.ServletException;importjavax.servlet.ServletRequest;importjavax.servlet.ServletResponse;importjavax.servlet.http.HttpServletRequest;
importorg.apache.struts2.dispatcher.StrutsRequestWrapper;
publicclass UploadFilter implementsFilter {
publicvoid destroy() {}
publicvoid doFilter(ServletRequest request, ServletResponse response,FilterChainchain)throws IOException, ServletException {chain.doFilter(new StrutsRequestWrapper((HttpServletRequest)request),response);}
publicvoid init(FilterConfig filterConfig) throws ServletException{}
}==========上传和管理服务器图片的类 My Code==========
《《《《《《《《《《《《《《《《 第二个问题json返回结果 》》》》》》》》》》》》》》》》》》》》》
上传返回结果json字符串本想用struts2的方式返回,但是失败(KindEditor脚本原因)改用上述方式成功.
我在使用时,是用jsp页面处理的上传过程,并没有做此复杂处理,最简单的修改方式:
(1)建立filter拦截器;(2)在web.xml设置对处理上传的jsp页面的filter(注:)
代码如下:
(1)UploadFilter:
package com.utils.contentfilter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.dispatcher.StrutsRequestWrapper;
public class UploadFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponseresponse,
FilterChain chain) throws IOException, ServletException {
chain.doFilter(new StrutsRequestWrapper((HttpServletRequest)request), response);
}
public void init(FilterConfig filterConfig) throws ServletException{
}
}
(2) web.xml中设置:
uploadsss
com.utils.contentfilter.UploadFilter
uploadsss
/upload_json.jsp