markdown 页面编辑器
为了不影响读者疲劳,我长话短说。
markdown 发表文章 : http://blog.csdn.net/qq_19558705/article/details/52121321
markdown 操作文章 : http://blog.csdn.net/qq_19558705/article/details/52171181
个人主页:http://www.itit123.cn/ 更多干货等你来拿
效果图:
我重点讲解插入图片
直接点击插入图片,会提示 “upload_image_url not defined.” 的错误,看源码后得知要自己配置上传图片路径。在markdown-edit.js最后几行中有。
这是我填写的,仅供参考:
upload_image_url: '/sierew/blog/uploadImage',
在该js的315行,我习惯的添加了一个 enctype="multipart/form-data"
+ '<div class="span" style="width:300px"><form enctype="multipart/form-data">'
从408行到422行的代码中可以看出,插入图片需要我们返回一个json格式的数据,key有message,error,url值。
下面是上传代码:
@RequestMapping(value = "uploadImage" , method = RequestMethod.POST)
@ResponseBody
public String uploadImage(HttpServletRequest request,
@RequestParam(value = "file" , required=false) MultipartFile file,
@RequestParam(value = "text" , required=false) String fileName) {
String realPath = request.getSession().getServletContext().getRealPath("/");
String resourcePath = "static\\images\\uploadImages\\";
String result = null;
if(file!=null){
if(GenerateUtils.allowUpload(file.getContentType())){
// 存储本地
File dir = new File(realPath + resourcePath);
if(!dir.exists()){
dir.mkdirs();
}
File saveFile = new File(dir,file.getOriginalFilename());
try {
file.transferTo(saveFile);
System.out.println("dir : " +dir);
String callbackImgUrl = WEB_PATH + request.getSession().getServletContext().getContextPath() + "/" +resourcePath.replaceAll("\\\\","/") + file.getOriginalFilename();
Map<String, Object> resultMap = new HashMap<String, Object>();
resultMap.put("message", fileName);
resultMap.put("url", callbackImgUrl);
result = new Gson().toJson(resultMap);
} catch (IllegalStateException e) {
e.printStackTrace();
result = "{\"error\":\"upload error\"}";
} catch (IOException e) {
e.printStackTrace();
result = "{\"error\":\"upload error\"}";
}
}
}
System.out.println("result : " +result);
return result;
}
代码解释:
WEB_PATH是访问的路径,我的是"http://ip:port" 。用的是Gson 将map转json
Gson maven
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.6.2</version>
</dependency>
这样就可以了,看了几百行的js代码,换来了短短的几行代码,为了不让其他人走弯路,贡献自己的微薄之力。
本人菜鸟,有什么不对的地方请指出,我会及时更改。
遇到的问题:
开始没打算用gson,打算自己拼接json格式的字符串,结果一直失败提示:SyntaxError: JSON.parse: unexpected character at line 6 column 1 of the JSON dat ,说什么我不按照格式来。
修改了格式后提示:SyntaxError: JSON.parse: expected property name or '}' at line 1 column 2 of the JSON data , 百度后发现是jquery解析json的时候,不识别单引号。 最后用gson一次成功。
XMLHttpRequest2 使用指南:http://www.ruanyifeng.com/blog/2012/09/xmlhttprequest_level_2.html
如果你的项目中用到了sitemesh , 建议将该页面屏蔽。
上传图片的效果图: