經過前面兩篇文章的鋪墊,接下來就是重點了,最原始的summernote的圖片上傳功能還未完善,現在我們要做的就是修改這個功能,使其功能完善派上用場。
summernote提供了一些方法的重寫,我們就來重寫其上傳圖片的方法onImageUpload,然後將data數據傳送到upload.do這個controller,data數據中包含了上傳圖片的名字。editor.insertImage()的作用是在編輯器中顯示已經上傳的圖片,第一個參數表示當前編輯器,第二個參數是圖片保存的路徑。
<script>
$(document).ready(function() {
$('#summernote').summernote({
height:300,
focus:true,
maxHeight:null,
minHeight:null,
onImageUpload: function(files, editor, welEditable) {
sendFile(files[0],editor,welEditable);
}
});
});
function sendFile(files,editor,welEditable) {
data = new FormData();
data.append("file", files);
$.ajax({
data: data,
type: "POST",
url: "/lol/upload.do",
cache: false,
contentType: false,
processData: false,
success: function(data) {
alert(data.fileName);
editor.insertImage(welEditable, "img/" + data.fileName);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.status);
alert(XMLHttpRequest.readyState);
alert(textStatus);
}
});
}
後臺代碼來了哦,其實就是一個簡單的springMvc上傳controller。着重強調:
@RequestMapping(value = "/upload.do")
public @ResponseBody Map upload(MultipartFile file, HttpServletRequest request) {
System.out.println("開始");
String path = request.getSession().getServletContext().getRealPath("/img");//項目中的img文件夾下
String fileName = file.getOriginalFilename();
// String fileName = new Date().getTime()+".jpg";
Map<String, Object> map = new HashMap<String, Object>();
map.put("fileName",fileName);
System.out.println(fileName);
System.out.println(path);
File targetFile = new File(path, fileName);
if(!targetFile.exists()){
targetFile.mkdirs();
}
//保存
try {
file.transferTo(targetFile);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(fileName);
return map;
}
@ResponseBody這個註解,一般來說controller中返回的數據就會被當作頁面的名字進行處理,我們這裏需要將返回的數據給ajax處理,而不是跳轉到某個頁面,這就是此註解的作用。
request.getSession().getServletContext().getRealPath();獲取項目的真實路徑,大家在eclipse中配置tomcat的時候別忘了將項目設置爲部署在tomcat下,如圖:
因爲用到了上傳,所以別忘了配置上傳用的jar包:
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
SpringMVC 用的是MultipartFile來進行文件上傳,所以我們首先要配置MultipartResolver:用於處理表單中的file:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
總結下,整個summernote至此功能基本齊全了,圖片會上傳到自己的tomcat裏,你的項目下的img文件夾內,ajax收到返回的文件名傳給editor.insertImage()方法,使上傳的圖片能夠在編輯器內顯示。這下,我們可以盡情享用summernote了。