拿到一个项目后台用ckeditor4,根据实际需求要添加上传图片功能。
具体步骤:
1、配置文件
在web/js/ckeditor/config.js配置文件中增加:(其中imageUpload是下面写的servlet的url)
config.filebrowserImageUploadUrl = "imageUpload";
2、编写servlet处理图片上传
public class ImageUploadServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
PrintWriter out=response.getWriter();
FileItemFactory factory=new DiskFileItemFactory();
ServletFileUpload upload=new ServletFileUpload(factory);
try {
List<FileItem> list=upload.parseRequest(request);
for(FileItem fileItem:list){
String imageName=DateUtil.getCurrentDateStr();
//DateUtil工具类获取当前日期时间字符串
File fileRealPathDirectory = new File(PropertiesUtil.getValue("imagePath")+imageName.substring(0,8));
//PropertiesUtil参数配置工具类,根据参数名获取参数值
//上传的文件路径,这里用参数配置中的值+日期时间的前8位(如20240219)
if (!fileRealPathDirectory.exists()) {//不存在,就创建
fileRealPathDirectory.mkdirs();//创建
}
File file=new File(fileRealPathDirectory+"/"+imageName.substring(8)+"."+fileItem.getName().split("\\.")[1]);
//保存的文件名:路径+/+日期时间的第9位到结束(如121301)+.+原来文件的扩展名
String newPath=PropertiesUtil.getValue("imageFile")+"/"+imageName.substring(0,8)+"/"+imageName.substring(8)+"."+fileItem.getName().split("\\.")[1];
//回传给前端的地址,根据实际情况修改
fileItem.write(file);
String callback = request.getParameter("CKEditorFuncNum");
out.println("<script type=\"text/javascript\">");
out.println("window.parent.CKEDITOR.tools.callFunction(" + callback + ",'" + newPath + "',''" + ")");
out.println("</script>");
out.flush();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
3、配置上传文件路径
imagePath=D:\\idea_java_projects\\nbxx\\web\\userImage\\
imageFile=userImage
4、eclipese热部署自动刷新设置