Java处理wangeditor上传图片并升级一下
作者:互联网
wangeditor上传图片
1.在页面上设置富文本编辑器
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="static/js/jquery-3.5.1.js"></script> <!--jquery拿来备用-->
<script src="static/js/wangEditor.min.js"></script> <!--引入wangEditor的js文件-->
<title>Insert title here</title>
</head>
<body>
<span>WANGEDITOR富文本编辑器</span>
<br>
<div id="myeditor" style="height: 600px;width: 800px">
<p>默认的值</p>
</div>
<script>
const E = window.wangEditor
const editor = new E('#myeditor') /*为富文本编辑器绑定显示的div容器*/
editor.config.uploadImgServer = '${pageContext.request.contextPath}/upload_img.do';
editor.config.uploadFileName = 'file';
/*设置编辑器上传文件的请求接口,和参数名称*/
editor.create() //创建wangeditor编辑器
</script>
</body>
</html>
2.wangeditor的上传图片返回格式的要求(官方文档)
接口返回格式,重要
接口要返回 application/json
格式,格式要求如下:
必须返回如下格式,图片才会回显,需要构造一个Vo类
{
// errno 即错误代码,0 表示没有错误。
// 如果有错误,errno != 0,可通过下文中的监听函数 fail 拿到该错误码进行自定义处理
"errno": 0,
// data 是一个数组,返回图片Object,Object中包含需要包含url、alt和href三个属性,它们分别代表图片地址、图片文字说明和跳转链接,alt和href属性是可选的,可以不设置或设置为空字符串,需要注意的是url是一定要填的。
"data": [
{
url: "图片地址",
alt: "图片文字说明",
href: "跳转链接"
},
{
url: "图片地址1",
alt: "图片文字说明1",
href: "跳转链接1"
},
"……"
]
}
wangEditor返回包装类
public class WangEditorVO {
//错误码
private Integer errno;
//data数据
private Object data;
public Integer getErrno() {
return errno;
}
public Object getData() {
return data;
}
public static WangEditorVO success(Object data) {
WangEditorVO wangEditorVO = new WangEditorVO();
wangEditorVO.errno = 0;
wangEditorVO.data = data;
return wangEditorVO;
}
public static WangEditorVO error(Integer errno, Object data) {
WangEditorVO wangEditorVO = new WangEditorVO();
wangEditorVO.errno = errno;
wangEditorVO.data = data;
return wangEditorVO;
}
}
3.编写上传图片接口(使用springMVC)
/**
*
* @ClassName: TestController
* @Description:TODO(描述这个类的作用)
* @author: 你的名字
* @date: 2021年9月16日 上午9:44:26
* @Copyright:
*/
@Controller
public class TestController {
/*上传图片接口*/
@RequestMapping("/upload_img.do")
@ResponseBody
public WangEditorVO UploadFileInWangEditor(@RequestParam("file") MultipartFile file) throws IllegalStateException, IOException { //接收上传的图片
String oldname = file.getOriginalFilename();
//保存到项目的upload目录下
file.transferTo(new File("E:\\vc++\\AllAnnoationTest\\WebContent\\upload","fucking"+oldname));
List<String> list = new ArrayList<String>();
//因为回显的图片使用src属性,必须使用url形式,不能使用绝对路径
String resource = "http://localhost:8082/AllAnnoationTest/upload/fucking"+oldname;
//放入list集合
list.add(resource);
return WangEditorVO.success(list); //创建Vo类并传入data属性,然后返回
}
}
4.测试,查看网页的控制台
5.升级,保存带图片的文章,(全注解JPA)
将内容保存到数据库中去(全注解使用JPA)
编写主配Class,DataSourceConfig
/**
*
* @ClassName: DataSourceConfig
* @Description: 配置数据源
* @author: 你的名字
* @date: 2021年9月17日 下午7:20:16
* @Copyright:
*/
@Configuration
@EnableAspectJAutoProxy() //开启自动代理
@EnableTransactionManagement //开启注解事务
public class DataSourceConfig {
/*配置C3P0数据源*/
@Bean
public DataSource dataSource() throws PropertyVetoException {
ComboPooledDataSource datasource = new ComboPooledDataSource();
datasource.setJdbcUrl("jdbc:mysql://localhost:3306/jpatest?useSSL=true&useUnicode=true&CharacterEncoding=UTF-8&serverTimeZone=UTC");
datasource.setDriverClass("com.mysql.cj.jdbc.Driver");
datasource.setUser("root");
datasource.setPassword("XXXXXXXXXXXXXXXXX");
return datasource;
}
/**
*
* @Title: entityManagerFactory
* @Description: 配置entityManageFatory(SessionFactory) Session工厂
* @param: @return
* @param: @throws PropertyVetoException
* @return: LocalContainerEntityManagerFactoryBean
* @throws
*/
@Bean
public EntityManagerFactory entityManagerFactory() throws PropertyVetoException {
LocalContainerEntityManagerFactoryBean enFactory = new LocalContainerEntityManagerFactoryBean();
enFactory.setDataSource(dataSource());
//设置JPA的Hibernate适配器
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(true);
//扫描实体类所在的包
enFactory.setJpaVendorAdapter(vendorAdapter);
enFactory.setPackagesToScan("com.anno.pojo");
//设置JPA的一些特性信息
Properties properties = new Properties();
properties.put("hibernate.show_sql", "true");
properties.put("hibernate.format_sql", "true");
properties.put("hibernate.dialect", "org.hibernate.dialect.MySQL8Dialect");
properties.put("hibernate.hbm2ddl.auto", "update");
enFactory.setJpaProperties(properties);
enFactory.afterPropertiesSet();
//用spring提供的转型转为符合JPA规范的EntityManageFactory接口的方法转型然后返回
return enFactory.getObject();
}
/*配置事务管理器*/
@Bean
public PlatformTransactionManager transactionManager() throws PropertyVetoException {
JpaTransactionManager manager = new JpaTransactionManager();
manager.setEntityManagerFactory(entityManagerFactory());
//设置JPA的事务管理器,注入Session工厂,(EntityManageFactory)
return manager;
}
}
(PS.WebMvc的配置)
/**
*
* @ClassName: WebMvcConfig
* @Description:配置SpringMVC
* @author: 黎翰
* @date: 2021年9月16日 上午9:29:51
* @Copyright:
*/
@Configuration
@ComponentScan("com.anno")
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {
/***
* 通过注解 @Bean 初始化视图解析器
* @return ViewResolver 视图解析器
*/
@Bean(name="internalResourceViewResolver")
public ViewResolver initViewResolver() {
InternalResourceViewResolver viewResolver =new InternalResourceViewResolver();
viewResolver.setPrefix("");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
/**
* 初始化RequestMappingHandlerAdapter,并加载Http的Json转换器
* @return RequestMappingHandlerAdapter 对象
*/
@Bean(name="requestMappingHandlerAdapter")
public HandlerAdapter initRequestMappingHandlerAdapter() {
//创建RequestMappingHandlerAdapter适配器
RequestMappingHandlerAdapter rmhd = new RequestMappingHandlerAdapter();
// HTTP JSON转换器
MappingJackson2HttpMessageConverter jsonConverter
= new MappingJackson2HttpMessageConverter();
//MappingJackson2HttpMessageConverter接收JSON类型消息的转换
MediaType mediaType = MediaType.APPLICATION_JSON_UTF8;
List<MediaType> mediaTypes = new ArrayList<MediaType>();
mediaTypes.add(mediaType);
//加入转换器的支持类型
jsonConverter.setSupportedMediaTypes(mediaTypes);
//往适配器加入json转换器
rmhd.getMessageConverters().add(jsonConverter);
return rmhd;
}
/**
*
* @Title: commonsMultipartResolver
* @Description: 配置上传文件解析器
* @param: @return
* @return: CommonsMultipartResolver
* @throws
*/
@Bean
public CommonsMultipartResolver multipartResolver() {
CommonsMultipartResolver resolver = new CommonsMultipartResolver();
resolver.setDefaultEncoding("UTF-8");
resolver.setMaxInMemorySize(1024*1024*10);
resolver.setMaxUploadSize(1024*1024*20);
return resolver;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("/static/");
registry.addResourceHandler("/upload/**").addResourceLocations("/upload/");
WebMvcConfigurer.super.addResourceHandlers(registry);
}
}
WebInit配置(代替的Web.xml)
/**
*
* @ClassName: WebInit
* @Description: 代替了Web.xml文件
* @author: 黎翰
* @date: 2021年9月16日 上午9:16:38
* @Copyright:
*/
public class WebInit extends AbstractAnnotationConfigDispatcherServletInitializer{
@Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] {WebMvcConfig.class};
}
@Override
protected String[] getServletMappings() {
return new String[] {"*.do"};
}
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
servletContext.addFilter("encodingFilter", MyencodingFilter.class)
.addMappingForUrlPatterns(null, false, "/*");
//必须调用父类的onStarup不然DispatchServlet不会加载
super.onStartup(servletContext);
}
}
dao层:
/**
*
* @ClassName: ArticleDaoImpl
* @Description:文章Dao的实现类
* @author: 黎翰
* @date: 2021年9月17日 下午8:04:11
* @Copyright:
*/
@Repository
public class ArticleDaoImpl implements ArticleDao{
@PersistenceContext
private EntityManager entityManager;//Session
@Override
public void SaveArticle(Article article) {
entityManager.persist(article);
}
@Override
public Article getArticle(Integer id) {
return entityManager.find(Article.class, id);
}
}
service层:
@Service
public class ArticleService {
@Autowired
private ArticleDao articleDao;
@Transactional
public void SaveArticle(Article article) {
articleDao.SaveArticle(article);
}
public Article getArticle(Integer id) {
return articleDao.getArticle(id);
}
}
pojo:
/**
*
* @ClassName: Article
* @Description:保存输入的文章pojo
* @author: 黎翰
* @date: 2021年9月17日 下午7:25:27
* @Copyright:
*/
@Entity
@Table(name="t_article")
public class Article {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="a_id")
private Integer id;
@Column(name="a_title")
private String title;
@Column(name="a_auther")
private String auther;
@Column(name="a_context",length=500)
private String context;
//-------------------省略Getter&Setter方法
}
控制层:
@RequestMapping("/submitArticle.do")
@ResponseBody
public String submitArticle(Article article) {
//调用业务层保存到数据库里去
articleService.SaveArticle(article);
System.out.println("标题为"+article.getTitle());
System.out.println("作者为"+article.getAuther());
System.out.println("内容为"+article.getContext());
return "提交成功";
}
页面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="static/js/jquery-3.5.1.js"></script>
<script src="static/js/wangEditor.min.js"></script>
<title>Insert title here</title>
</head>
<body>
<span>WANGEDITOR富文本编辑器--------------------------------------------------</span><br>
<span>标题</span><input id="theTitle" type="text" name="title" /><br>
<span>作者</span><input id="theAuther" type="text" name="auther" />
<div id="myeditor" style="height: 600px;width: 800px">
<p>默认的值</p>
</div>
<script>
const E = window.wangEditor
const editor = new E('#myeditor')
editor.config.uploadImgServer = '${pageContext.request.contextPath}/upload_img.do';
editor.config.uploadFileName = 'file';
editor.create();
</script>
<!-- 用一个按钮来提交AJAX,帮个AJAX函数 -->
<input id="sub" type="button" οnclick="AJAXsubmit()" value="提交文章">
<script>
var AJAXsubmit = function(){
$.ajax({
url:"${pageContext.request.contextPath}/submitArticle.do",
type:"POST",
data:{"title":$('#theTitle').val(),"auther":$('#theAuther').val(),"context":editor.txt.html()},
success:function(result){
alert(result);
}
});
}
</script>
</body>
</html>
测试:
6.查看保存的文章,是否能正常显示图片
前提:和Spring和整合Hibernate一样,Spring为Hibernate提供了OpenSessionInViewFilter(懒加载拦截器)
让Hibernate的懒加载机制,能够在视图层才发送sql语句进行查询,
Spring也为JPA提供了类似的懒加载拦截器,可以在spring-orm包的jpa子包中看到
现在需要配置上Filter,在WebInit类中注册EntityManageInViewFilter,
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
//自定义的字符编码过滤器
servletContext.addFilter("encodingFilter", MyencodingFilter.class)
.addMappingForUrlPatterns(null, false, "/*");
//配置懒加载拦截器
servletContext.addFilter("openEntityManagerInView", OpenEntityManagerInViewFilter.class)
.addMappingForUrlPatterns(null, false, "/*");
//必须调用父类的onStarup不然DispatchServlet不会加载
super.onStartup(servletContext);
}
现在编写请求,将数据库里的文章显示出来
@RequestMapping("/testaction.do")
public String test1(Model model) {
//调用业务对象,查询t_article的指定id文章
Article myarticle = articleService.getArticle(2);
model.addAttribute("myarticle", myarticle);
return "success";
}
在页面里显示一下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<span>标题:</span>${myarticle.title}<br>
<span>作者:</span>${myarticle.auther}<br>
${myarticle.context}
</body>
</html>
```![请添加图片描述](https://www.icode9.com/i/ll/?i=00bba0d67f364f41bdb9278e3ebb10cf.png?,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA572X6ams6IuP5Li56buY572V6buY5b63,size_20,color_FFFFFF,t_70,g_se,x_16)
标签:return,wangeditor,data,class,new,Java,article,上传,public 来源: https://blog.csdn.net/jamenu/article/details/120358942