最近在用新的jfinal框架写个网站,之前用struts2 完成了ckeditor的上传功能。这次继续使用jfinal来做ckeditor的上传功能。
首先需要在controller中写上传的方法。如果我们在访问这个controller的时候不指定具体方法,默认是进入index方法。这个controller只用来上传,我们直接将方法写在index中。
public class UploadController extends Controller {
public void index() {
String path = PathKit.getWebRootPath().replace("\\", "/");
path = path+"/upload/";// upload 为自定义的保存路径
UploadFile file = getFile("upload",path,5* 1024 * 1024,"UTF-8");
String imgurl="";
Long fileName = System.currentTimeMillis();
if(file!=null){
String sufName = file.getFileName().substring(file.getFileName().lastIndexOf("."),file.getFileName().length());
String imgPath = path+fileName+sufName;
File dest = new File(imgPath);
imgurl="/upload/"+fileName+sufName;
file.getFile().renameTo(dest);
String callback =getPara("CKEditorFuncNum");
ConfigLoad con = new ConfigLoad();
String url=con.imgURL(); //这里是我从外部配置文件取得的url地址,你可以直接换成自己的地址
PrintWriter writer = null;
try {
HttpServletResponse response = getResponse();
String fullContentType ="text/html;charset=UTF-8";
response.setContentType(fullContentType); //定义contentType格式,否则可能字符会被转义,上传后的图片地址无法自动写入
writer = response.getWriter();
writer.write("<script type=\"text/JavaScript\">"
+"window.parent.CKEDITOR.tools.callFunction("+ callback + ",'" + "http://"+url + imgurl + "','')"
+"</script>");
writer.flush();
} catch (IOException e) {
throw new RenderException(e);
}
finally {
if (writer != null)
writer.close();
}
}
render("your.jsp");
}
}
在jfinal的configRoute方法中配置路由。添加下面一段代码
add里的第一个参数就是这个controller的请求地址,也就是这个controller类存放的绝对路径。
me.add("yourpath/controller/UploadController", UploadController.class,"/yourself");
在ckeditor的config.js的CKEDITOR.editorConfig = function( config )中添加下面一段代码。指定上传的请求地址,跟上面的第一个参数一样。
config.filebrowserUploadUrl="yourpath/controller/UploadController";
图片和文件上传都可以用该controller。