注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

放飞自由

年轻人,如果三年的时间里,没有任何想法,他这一生,就基本这个样子,没有多大改变。

 
 
 

日志

 
 

struts2 + kindeditor上传图片+管理图片  

2012-02-10 11:07:34|  分类: WEB前端 |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |
kindeditor struts 上传图片
http://blog.csdn.net/alinaxz/article/details/6597516
http://wsfly.iteye.com/blog/997791
http://dsea.iteye.com/blog/1068863
http://www.cnitblog.com/intrl/archive/2009/04/18/56447.html
http://topic.csdn.net/u/20110625/14/bc104e1b-1af8-4adf-825e-a389edd837be.html
http://topic.csdn.net/u/20090514/10/ba62c761-e591-4c9e-859a-87907634ea13.html
http://topic.csdn.net/u/20090514/10/ba62c761-e591-4c9e-859a-87907634ea13.html
http://www.iteye.com/
http://www.iteye.com/news/23482


struts2 + 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、按照网上找到对该问题的相关处理方法: 
<filter-mapping>
  <filter-name>struts2</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

修改为 :

<filter-mapping>
  <filter-name>struts2</filter-name>
  <url-pattern>*.action</url-pattern>
</filter-mapping>

hzq ps:当我遇到这个问题的时候我按照这个方法尝试了一下结果并没有解决我的问题

2、我的处理方法 
对于第1钟处理方式,网友们的意思应该是别让请求经过struts2,免得inputStream被提前读取了。虽然这样可以正常使用common-fileupload了,但这样就不经过struts2的拦截器了,而我又想让它拦一次,于是,我自己实现一个servlet.Filter,并且把它的filter次序放到struts2的filter次序之前。主要源码如下: 

public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
chain.doFilter(new StrutsRequestWrapper((HttpServletRequest) request), response);
}
这里先用StrutsRequestWrapper来给他wrapper一次,这样在经过struts2的filter的时候就不会有问题了。为啥呢?可以自己看看这个类 
org.apache.struts2.dispatcher.Dispatcher里面的wrapRequest方法,有这么个判断: 

// don't wrap more than once
if (request instanceof StrutsRequestWrapper) {
return request;
}
http://commons.apache.org/fileupload/faq.html#top

Why is parseRequest() returning no items?

This most commonly happens when the request has already been parsed, or processed in some other way. Since the input stream has aleady been consumed by that earlier process, it is no longer available for parsing by Commons FileUpload.

hzq ps:我也不太理解
-----------------------------------------------------------------------------------------------

==========上传和管理服务器图片的类 My Code ==========

import java.util.*;
import java.io.*;

import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.*;
import org.apache.commons.fileupload.servlet.*;

import java.text.SimpleDateFormat;
import org.json.simple.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Controller;

import com.huawei.ciss.common.utils.StringUtils;
import com.huawei.ciss.common.utils.SystemConfig;
import com.huawei.ciss.model.Sys_user;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

/**
 * 图片文件上传/管理
 * 
 * @author HKF60605
 */
@Controller
@SuppressWarnings("unchecked")
public class ImageManagerAction extends ActionSupport {

private static final long serialVersionUID = 1L;
private static final int UPLOAD_MSG_SUCCESS = 0;
private static final int UPLOAD_MSG_FAIL = 1;

/**
* 上传文件
*/
public String uploadImage() throws Exception {
Sys_user user = getLoginUserInfo();
HttpServletResponse response = ServletActionContext.getResponse();
HttpServletRequest request = ServletActionContext.getRequest();
response.setContentType("text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
String configPath = SystemConfig.getString("configPath");
// 文件保存目录路径(如:D:\Program Files\Tomcat 6.0\webapps\editor\")
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<String, String> extMap = new HashMap<String, String>();
extMap.put("image", SystemConfig.getString("allow_file_img"));
// 最大文件大小
long maxSize = Long.parseLong(SystemConfig.getString("maxSize"));

if (!ServletFileUpload.isMultipartContent(request)) {
return getError("请选择文件。");
}
// 检查目录
File uploadDir = new File(savePath);
if (!uploadDir.isDirectory()) {
uploadDir.mkdirs();
}
// 检查目录写权限
if (!uploadDir.canWrite()) {
return getError("上传目录没有写权限。");
}

String userName = user.getLoginId();
if(StringUtils.isEmpty(userName)){
return getError("登录账号为空,无法找到对应的上传文件目录。");
}
// 创建文件夹
savePath += userName + "/";
saveUrl += userName + "/";
File saveDirFile = new File(savePath);
if (!saveDirFile.exists()) {
saveDirFile.mkdirs();
}
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()) {
FileItem item = (FileItem) itr.next();
String fileName = item.getName();
if (!item.isFormField()) {
// 检查文件大小
if (item.getSize() > maxSize) {
return getError("上传文件大小超过限制。");
}
// 检查扩展名
String fileExt = fileName.substring(
fileName.lastIndexOf(".") + 1).toLowerCase();
if (!Arrays.<String> asList(extMap.get("image").split(","))
.contains(fileExt)) {
return getError("上传文件扩展名是不允许的扩展名。\n只允许"+ extMap.get("image") + "格式。");
}

SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
try {
File uploadedFile = new File(savePath, newFileName);
item.write(uploadedFile);
} catch (Exception e) {
return getError("上传文件失败。");
}

JSONObject obj = new JSONObject();
obj.put("error", UPLOAD_MSG_SUCCESS);
obj.put("url", saveUrl + newFileName);
System.out.println(obj.toJSONString() + "----------------");
out.println(obj.toJSONString());
}
}
return null;
}

/** 
* 文件管理
*/
public String managerImage() throws Exception {
Sys_user user = getLoginUserInfo();
HttpServletResponse response = ServletActionContext.getResponse();
HttpServletRequest request = ServletActionContext.getRequest();
response.setContentType("text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
String configPath = SystemConfig.getString("configPath");
// 文件保存目录路径(如:D:\Program Files\Tomcat 6.0\webapps\editor\")
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"};

String dirName = user.getLoginId();
if (dirName != null) {
rootPath += dirName + "/";
rootUrl += dirName + "/";
File saveDirFile = new File(rootPath);
if (!saveDirFile.exists()) {
saveDirFile.mkdirs();
}
}
//根据path参数,设置各路径和URL
String 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 or type
String order = request.getParameter("order") != null ? request.getParameter("order").toLowerCase() : "name";

//不允许使用..移动到上一级目录
if (path.indexOf("..") >= 0) {
out.println("Access is not allowed.");
return null;
}
//最后一个字符不是/
if (!"".equals(path) && !path.endsWith("/")) {
out.println("Parameter is not valid.");
return null;
}
//目录不存在或不是目录
File currentPathFile = new File(currentPath);
if(!currentPathFile.isDirectory()){
out.println("Directory does not exist.");
return null;
}

//遍历目录取的文件信息
List<Hashtable> fileList = new ArrayList<Hashtable>();
if(currentPathFile.listFiles() != null) {
for (File file : currentPathFile.listFiles()) {
Hashtable<String, Object> hash = new Hashtable<String, Object>();
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", "");
} else if(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.<String>asList(fileTypes).contains(fileExt));
hash.put("filetype", fileExt);
}
hash.put("filename", fileName);
hash.put("datetime", new SimpleDateFormat("yyyy-MM-dd HH: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());
}
JSONObject result = 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());
return null;
}
public class NameComparator implements Comparator {
public int compare(Object a, Object b) {
Hashtable hashA = (Hashtable)a;
Hashtable hashB = (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"))) {
return 1;
} else {
return ((String)hashA.get("filename")).compareTo((String)hashB.get("filename"));
}
}
}
public class SizeComparator implements Comparator {
public int compare(Object a, Object b) {
Hashtable hashA = (Hashtable)a;
Hashtable hashB = (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"))) {
return 1;
} else {
if (((Long)hashA.get("filesize")) > ((Long)hashB.get("filesize"))) {
return 1;
} else if (((Long)hashA.get("filesize")) < ((Long)hashB.get("filesize"))) {
return -1;
} else {
return 0;
}
}
}
}
public class TypeComparator implements Comparator {
public int compare(Object a, Object b) {
Hashtable hashA = (Hashtable)a;
Hashtable hashB = (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"))) {
return 1;
} else {
return ((String)hashA.get("filetype")).compareTo((String)hashB.get("filetype"));
}
}
}
/**
* 错误信息
* @throws IOException 
*/
private String getError(String message) throws IOException {
JSONObject obj = new JSONObject();
obj.put("error", UPLOAD_MSG_FAIL);
obj.put("message", message);
ServletActionContext.getResponse().getWriter().println(obj.toJSONString());
return null;
}

private Sys_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#########

import java.util.MissingResourceException;
import java.util.ResourceBundle;

public class SystemConfig {

private static final String BUNDLE_NAME = "SystemConfig";

private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
.getBundle(BUNDLE_NAME);

private SystemConfig() {
}

/**
* get the value from the properties file
* @param key
*  the key in the properties file
* @return
*/
public static String getString(String key) {
try {
return RESOURCE_BUNDLE.getString(key);
} catch (MissingResourceException e) {
return "no " + key + " key!";
}
}
public static void main(String[] args) {
System.out.println(SystemConfig.getString("pwd.reset"));
}
}

#######################################################SystemConfig#########


web.xml  == 把此filter次序放到struts2的filter次序之前

<filter>
<filter-name>upload</filter-name>
<filter-class>com.huawei.ciss.common.web.UploadFilter</filter-class>
</filter>

<filter-mapping>
<filter-name>upload</filter-name>
<url-pattern>/ajaxImg_uploadImage.do</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>upload</filter-name>
<url-pattern>/ajaxImg_managerImage.do</url-pattern>
</filter-mapping>



==filter

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, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
chain.doFilter(new StrutsRequestWrapper((HttpServletRequest) request), response);  
}

public void init(FilterConfig filterConfig) throws ServletException {
}

}

==========上传和管理服务器图片的类 My Code ==========


《《《《《《《《《《《《《《《《  第二个问题  json返回结果 》》》》》》》》》》》》》》》》》》》》》

上传返回结果json字符串本想用struts2的方式返回,但是失败(KindEditor脚本原因)改用上述方式成功.


《《《《《《《《《《《《《《《《  第二个问题  图片保存路径+虚拟目录》》》》》》》》》》》》》》》》》》》》》

方式1:


方式2:自己上网搜去






  评论这张
 
阅读(2248)| 评论(0)
推荐 转载

历史上的今天

在LOFTER的更多文章

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2017