1.在form中,提交enctype=“multipart/form-data”的数据时,需要对springmvc对multipart类型的数据进行解析。
在springmvc.xml中,配置multipart类型的解析器:
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置上传文件的最大尺寸为5MB -->
<property name="maxUploadSize">
<value>5242880</value>
</property>
</bean>
并且加入上传文件的jar包依赖:
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
如果不配置,会导致参数绑定失败,参数传不进来
2.wangeditor:
<!-- css -->
<style type="text/css">
.tool {
border: 1px solid #ccc;
width : 80% ;
margin: 0 auto;
}
.editor {
border: 1px solid #ccc;
}
</style>
<!-- 编辑器 -->
<div>
<!-- 工具栏 -->
<div id="tool" class="tool" style="width: 80%; margin: 0 auto;"></div>
<hr>
<!-- 编辑框,min-height属性可以实现自动加长编辑框 -->
<div id="editor" class="editor" style="width: 80%;min-height: 400px; margin: 0 auto;"></div>
<br>
</div>
js:
注意指定的名称以及上传成功后回显的url地址
var E = window.wangEditor
var editor = new E('#tool','#editor') ;
// 或者 var editor = new E( document.getElementById('editor') )
editor.customConfig.showLinkImg = false
editor.customConfig.uploadFileName = 'file'
editor.customConfig.uploadImgServer = '../Contents/addPhoto.action'
editor.customConfig.uploadImgHooks = {
customInsert: function (insertImg, result, editor) {
var url =result.data;
alert(url) ;
insertImg("../../"+url);
}
}
editor.create();
3.controller中:
@RequestMapping("addPhoto")
@ResponseBody
public Map<String, String> addPhoto( MultipartFile file, HttpServletRequest request,HttpServletResponse response) throws Exception {
//得到文件名
String fileName=file.getOriginalFilename();
System.out.println(fileName);
//文件名后缀
String filePrefixname=fileName.substring(fileName.lastIndexOf("."));
//用uuid作为文件名
String newFilename = UUID.randomUUID()+filePrefixname ;
//保存到本地的文件夹
String savePath = "/file/photo/" ;
//转换成File
byte [] bytes = file.getBytes() ;
File photoPath = new File(savePath) ;
if(!photoPath.exists()) {
photoPath.mkdir() ;
}
//保存到本地
File photo = new File(savePath,newFilename) ;
FileCopyUtils.copy(bytes, photo);
//回显路径
String showPath = "photo\\"+newFilename ;
Map<String, String> map = new HashMap<>() ;
map.put("data", showPath) ;
return map ;
}