与1相比,就是将上传图片的功能也放到Action 中。参考这位仁兄的博客:http://www.cnblogs.com/java_cSharp/archive/2011/08/06/KindEditor_upload_image_plugin.html
基本上都是用他的代码。
一、我的Action 代码如下:
import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.Random; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.ServletActionContext; import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper; import org.aspectj.util.FileUtil; import org.json.simple.JSONObject; import sun.rmi.runtime.Log; import com.fxoh.ORM.FxhProductInfo; import com.fxoh.service.ProductInfoService; import com.sun.org.apache.commons.logging.LogFactory; public class AdminViewOrUpdateDetailAction { public File getImgFile() { return imgFile; } public void setImgFile(File imgFile) { this.imgFile = imgFile; } public String getImgFileFileName() { return imgFileFileName; } public void setImgFileFileName(String imgFileFileName) { this.imgFileFileName = imgFileFileName; } public String getImgHeight() { return imgHeight; } public void setImgHeight(String imgHeight) { this.imgHeight = imgHeight; } public String getAlign() { return align; } public void setAlign(String align) { this.align = align; } public String getImgTitle() { return imgTitle; } public void setImgTitle(String imgTitle) { this.imgTitle = imgTitle; } public ProductInfoService getProductInfoService() { return productInfoService; } public void setProductInfoService(ProductInfoService productInfoService) { this.productInfoService = productInfoService; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getDetailInfo() { return detailInfo; } public void setDetailInfo(String detailInfo) { this.detailInfo = detailInfo; } private int id; private String detailInfo; private ProductInfoService productInfoService; private File imgFile; /** 文件名称 */ private String imgFileFileName; /**图片宽度/ private String imgWidth; /*** 图片高度14*/ private String imgHeight; /** 图片对齐方式*/ private String align; /**2图片标题24 */ private String imgTitle; com.sun.org.apache.commons.logging.Log log = LogFactory.getLog(this.getClass());; //action的具体方法 public String uploadImg() { HttpServletRequest request = ServletActionContext.getRequest(); HttpServletResponse response = ServletActionContext.getResponse(); response.setContentType("text/html; charset=UTF-8"); // 文件保存目录路径 String savePath = ServletActionContext.getServletContext().getRealPath("/") + "attached/"; // 文件保存目录URL String saveUrl = request.getContextPath() + "/attached/"; // 定义允许上传的文件扩展名 String[] fileTypes = new String[] { "gif", "jpg", "jpeg", "png", "bmp" }; // 最大文件大小 long maxSize =2*1024*1024; PrintWriter out = null; try { out = response.getWriter(); } catch (IOException e1) { log.error(e1); } if (imgFile == null) { 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; } // 创建文件夹 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(); } String fileExt = imgFileFileName.substring(imgFileFileName.lastIndexOf(".") + 1).toLowerCase(); if (!Arrays.<String> asList(fileTypes).contains(fileExt)) { out.println(getError("上传文件扩展名[" + fileExt + "]是不允许的扩展名。")); return null; } if (imgFile.length() > maxSize) { out.println(getError("[ " + imgFileFileName + " ]超过单个文件大小限制,文件大小[ " + imgFile.length() + " ],限制为[ " + maxSize + " ] ")); return null; } SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt; File uploadedFile = new File(savePath, newFileName); try { FileUtil.copyFile(imgFile, uploadedFile); JSONObject obj = new JSONObject(); obj.put("error", 0); obj.put("url", saveUrl + newFileName); log.debug(obj); out.println(obj.toString()); log.debug("上传图片:[" + uploadedFile.getName() + "]" + ">>>[" + newFileName + "]成功"); } catch (IOException e) { log.error("图片上传失败:" + e); } return null; } private String getError(String message) { JSONObject obj = new JSONObject(); obj.put("error", 1); obj.put("message", message); log.debug(obj); return obj.toString(); } //将kindeditor里编辑的商品的详细信息保存到数据库中 public String saveDetailInfo(){ try{ FxhProductInfo fxhProductInfo=productInfoService.loadById(id); fxhProductInfo.setDetaileInfo(detailInfo); productInfoService.saveOrUpdate(fxhProductInfo); }catch(Exception e){ e.printStackTrace(); return "error"; } return "saveOK"; } }
二、说明一下:在struts2中action获取文件的时候: 页面<input type="file" name="imgFile">(哪里来的这个?参看你下载官方压缩包中的:plugins\image\image.html)
取文件名的话你的属性要这么写:页面file对象的name+FileName
取文件类型的话你的属性要这么写:页面file对象的name+ContentType
三、页面上的js就要这样写:
<script charset="utf-8" src="/EbusinessOfFxoh/kindeditor/kindeditor.js"></script>
<script>
KE.show({
id : 'detaileInfo', /* textarea的id */
imageUploadJson : 'adminVOUdetail_uploadImg', /*这里就是你上传图片的Action了,你应该能看出这是用通配符定义的吧*/
fileManagerJson : '/EbusinessOfFxoh/kindeditor/jsp/file_manager_json.jsp',
allowFileManager : true,
afterCreate : function(id) {
KE.event.ctrl(document, 13, function() {
KE.util.setData(id);
document.forms['example'].submit(); /*examp就是form 的名称了*/
});
KE.event.ctrl(KE.g[id].iframeDoc, 13, function() {
KE.util.setData(id);
document.forms['example'].submit();
});
}
});
</script>
四、用form 把textarea包起来
<form name="example" method="post" action="adminVOUdetail_saveDetailInfo?id=${fpi.id}" >
<textarea id="detaileInfo" name="detailInfo" style="width:600px;height:250px;" class="info">
${fpi.detaileInfo}
</textarea><br /><center>
<input type="submit" value=" 提 交 " />
<input type="reset" value=" 取 消 " /></center>
</form>
id=${fpi.id},这个你不用管,是我传的参数,不然Action怎么知道把商品的详细信息保存到数据库中的哪个记录中去呢?
五、总结:由于都是用别人的代码,感觉有点乱。他和kindeditor的官方的演示的例子一样,是将图片保存到项目的 attached文件夹下,当天上传的图片是放在该文件夹下的以当天日期命名的子文件夹下的。之前做过一个上传图片的功能,这和我的项目的要求不一样,另外图片的命名方式也和我的不一样。
另外说明一下,有时候并不一定要使用本地图片上传的功能。我觉得我这里就是这样,我的KE是给后台管理员添加商品的详细说明用的,而我已经做了图片上传的功能,所以这里没有必要再做图片上传了,只要让管理员到服务器上去找相应的图片就好了。关闭本地图片上传的功能,只要在第三步加上:allowUpload:false,就行了。我认为这样很符合逻辑,也方便多了。