最近在做博客系统,其中添加文章需要上传文章图片,在使用wangEditor富文本编辑器上传图片的时候遇到了一些坑,故此记录下来。先上效果图:
页面:只需引用wangEditor的js文件
<!DOCTYPE html>
<html xmlns="http://www.w3/1999/xhtml"
xmlns:th="http://www.thymeleaf"
xmlns:sec="http://www.thymeleaf/thymeleaf-extras-springsecurity4">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!-- Bootstrap 3.3.7 -->
<link rel="stylesheet" href="dist/css/wangEditor.min.css">
<title> wangEditor 测试</title>
</head>
<body>
<div id="div1">
<p>欢迎使用 <b>wangEditor</b> 富文本编辑器</p>
</div>
<textarea id="text1" style="width:100%; height:200px;display: none;" ></textarea>
<!-- 注意, 只需要引用 JS,无需引用任何 CSS !!!-->
<!-- jQuery 3 -->
<script src="bower_components/jquery/dist/jquery.min.js"></script>
<!-- wangEditor富文本编辑器 -->
<script type="text/javascript" src="dist/js/wangEditor.min.js"></script>
<script type="text/javascript">
var E = window.wangEditor
var editor = new E('#div1')
var $text1 = $('#text1')
editor.customConfig.onchange = function (html) {
// 监控变化,同步更新到 textarea
$text1.val(html)
}
//设置上传的参数名
editor.customConfig.uploadFileName = 'file';
// 上传图片到服务器
editor.customConfig.uploadImgServer = 'http://localhost:8080/uploadFile '
// 将图片大小限制为 10M
editor.customConfig.uploadImgMaxSize = 10 * 1024 * 1024;
editor.create()
// 初始化 textarea 的值
$text1.val(editor.txt.html())
</script>
</body>
</html>
wangEditor官方文档要求接口返回的格式如下:因此需要准备实体类接口返回的数据
{
// errno 即错误代码,0 表示没有错误。
// 如果有错误,errno != 0,可通过下文中的监听函数 fail 拿到该错误码进行自定义处理
"errno": 0,
// data 是一个数组,返回若干图片的线上地址
"data": [
"图片1地址",
"图片2地址",
"……"
] }
准备返回的对象
public class WangEditor {
private Integer errno; //错误代码,0 表示没有错误。
private String[] data; //已上传的图片路径
public WangEditor() {
super();
}
public WangEditor(String[] data) {
super();
this.errno = 0;
this.data = data;
}
public Integer getErrno() {
return errno;
}
public void setErrno(Integer errno) {
this.errno = errno;
}
public String[] getData() {
return data;
}
public void setData(String[] data) {
this.data = data;
}
@Override
public String toString() {
return "WangEditor [errno=" + errno + ", data=" + Arrays.toString(data)
+ "]";
}
}
Controller
@Controller @Slf4j public class UploadFileController {
@RequestMapping(value = "/uploadFile",method = RequestMethod.POST)
@ResponseBody
public WangEditor uploadFile(@Param("file")MultipartFile file) {
//本地使用,上传位置
String rootPath ="D://uploads//";
//文件的完整名称,如spring.jpeg
String filename = file.getOriginalFilename();
//文件名,如spring
String name = filename.substring(0,filename.indexOf("."));
//文件后缀,如.jpeg
String suffix = filename.substring(filename.lastIndexOf("."));
//目标文件
File descFile = new File(rootPath+File.separator+File.separator+filename);
int i = 1;
//若文件存在重命名
String newFilename = filename;
while(descFile.exists()) {
newFilename = name+"("+i+")"+suffix;
String parentPath = descFile.getParent();
descFile = new File(parentPath+File.separator+newFilename);
i++;
}
//判断目标文件所在的目录是否存在
if(!descFile.getParentFile().exists()) {
//如果目标文件所在的目录不存在,则创建父目录
descFile.getParentFile().mkdirs();
}
//将内存中的数据写入磁盘
try {
file.transferTo(descFile);
} catch (Exception e) {
e.printStackTrace();
log.error("上传失败,cause:{}",e);
}
//完整的url
String fileUrl = "http://localhost:8080/uploads/"+newFilename;
//System.out.println(fileUrl);
String[] data = { fileUrl };
WangEditor we = new WangEditor(data);
return we;
} }
这样上传图片本地电脑有显示图片,而页面会报图片上传错误,这里就涉及虚拟路径和绝对路径的问题,需要将虚拟路径和绝对路径进行映射,这样做的好处是将实际的D:\uploads路径映射成tomcat下的/uploads路径,当你启动服务器时,访问http://localhost:8080/uploads/IMG_20180523_204538.0038.jpg,就能访问到你实际保存在D:\uploads下的文件,IMG_20180523_204538.0038.jpg是我的D盘下\uploads下的文件。
@Configuration
public class MyWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter {
//..........此处省略其他
//文件上传虚拟路径和绝对路径映射
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/uploads/**").addResourceLocations("file:D:/uploads/");
}
}
另外,服务器默认的最大上传大小比较小,可以自己设置最大文件大小,我是在启动类设置的
@SpringBootApplication
@EnableTransactionManagement // 启注解事务管理,等同于xml配置方式的 <tx:annotation-driven />
@MapperScan("com.zhuang.myblog.dao")
public class MyblogApplication {
public static void main(String[] args) {
SpringApplication.run(MyblogApplication.class, args);
}
/**
* 文件上传
*/
@Bean
MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
// 单个数据大小,10M
factory.setMaxFileSize("10240KB"); // KB,MB
return factory.createMultipartConfig();
}
}
更多推荐
富文本编辑器上传图片(及上传后图片不回显处理)
发布评论