spring mvc+xheditor图片上传

2023-10-28 03:59

本文主要是介绍spring mvc+xheditor图片上传,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!



用户发表文章(Post),在xheditor中写文字和上传图片,交叉进行,图片文件上传到了服务器,图片的名称,url,大小等信息在上传的同时需要单独保存在一张表里。

因此在上一篇的UploadController中除了做上传图片这事之外,还要向Attachment记录图片信息。修改代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
@Controller
@RequestMapping ( "/upload" )
public class UploadController {
     private static final Log logger = LogFactory.getLog(UploadController. class );
     @Autowired
     private AttachmentService attachmentService;
     @RequestMapping (value = "/image" , method = RequestMethod.POST)
     @ResponseBody
     public String image(HttpServletRequest request,
             HttpSession session,
             @RequestParam ( "filedata" ) MultipartFile file) throws Exception {
         // 将图片按日期分开存放,方便管理
         final String prefix = "upload/images/"
                 + DateUtil.getFormatedDate( "yyyy/MM_dd" );
         // 存放到web根目录下,如果日期目录不存在,则创建,
         // 注意 request.getRealPath("/") 已经标记为不推荐使用了.
         final String realPath = session.getServletContext().getRealPath(prefix);
         logger.info(realPath);
         File dir = new File(realPath);
         if (!dir.exists()) {
             dir.mkdirs();
         }
         // 以下是真正的上传部分
         String error = "" ;
         // 取得原文件名
         String originName = file.getOriginalFilename();
         // 取得文件后缀
         String fileExt = originName.substring(originName.lastIndexOf( "." ) + 1 );
         // 按时间戳生成图片文件名
         String picture = DateUtil.getFormatedDate( "yyyyMMddHHmmss" ) + "."
                 + fileExt;
         Attachment attachment = new Attachment();
         try {
             IOUtils.copy(file.getInputStream(), new FileOutputStream( new File(dir, picture)));
             //向attachment表中插入一条post_id为空的图片记录
             attachment.setDownloadCount( 0 );
             attachment.setSize(( int ) file.getSize());
             attachment.setUrl(prefix + "/" + picture);
             attachment = attachmentService.createAttachment(attachment);
         } catch (Exception e) {
             logger.error( "error:" , e);
             error = e.getMessage();
         }
         String http = "http://" + request.getServerName()
                     + ":" 
                     + request.getServerPort()     
                     + request.getContextPath();  
         String url =  http + "/" + prefix + "/" + picture;
         //注意这里的格式(见xheditor文档)
         //{'err':'',msg:{'url':'XXX/upload/images/2012/11_11/20121111015039.jpg','localname':'我的头像.jpg','id':'63'}}
         String json = String.format( "{'err':'%s',msg:{'url':'%s','localname':'%s','id':'%s'}}" ,
                                              error, url, originName, attachment.getId());
         return json;
     }
}

稍微解释一下xheditor json字符串中几个参数的作用::

(1)err:当这个值不为空时,xheditor会在JSP中弹出一个上传失败的对话框并显示err的内容
(2)url: 最终拼凑的可在浏览器中访问的http图片地址,xheditor直接根据这个值在editor中显示图片
(3)localname:这个值不是必须的,一般用来存储图片的名字,是url中的最后部分(也可以不是,比如我url中的图片名字是用时间戳命名的,而这里localname是图片本身的名字)
(4)id:这个值不是必须的,它代表图片在attachment表中的id,回传到JSP,当发表文章做进一步的处理

这张表Attachment和Post是多对一关系,Attachment表中有一个post_id,问题是:保存图片信息的时候, post_id还不存在(用户还没有提交Post呢),

怎么办呢?

我们可以在每次上传时插入一条没有post_id的图片记录,等到用户真正发表文章的时候,批量更新这些attachment的post_id,相关代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
@Override
public void updateAttachmentsWithPostId(List<Attachment> attchments, Long postId) {
     List<Object[]> batchArgs = new ArrayList<Object[]>();
     if (attchments != null ) {
         for (Attachment attachment : attchments) {
             Object[] args = new Object[] { postId, attachment.getId() };
             batchArgs.add(args);
         }
     }
     String sql = "update cms_attachment set post_id = ? where id=?" ;
     jdbcTemplate.batchUpdate(sql, batchArgs);
}

其间解决了一个@ResponseBody乱码问题(json字符串中的localname为中文时回传到JSP中是乱码)
在这里找到了解决办法:http://www.oschina.net/code/snippet_103691_11482,加入了如下配置:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!-- 解决@ResponseBody乱码问题, 需要在annotation-driven之前并且spring版本需要3.1.2以上 -->
<!--Spring3.1推荐使用RequestMappingHandlerAdapter -->
< bean
     class = "org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" >
     < property name = "messageConverters" >
         < list >
             < bean
                 class = "org.springframework.http.converter.ByteArrayHttpMessageConverter" />
             < bean
                 class = "org.springframework.http.converter.StringHttpMessageConverter" >
                 < property name = "supportedMediaTypes" >
                     < list >
                         < value >text/plain;charset=UTF-8</ value >
                     </ list >
                 </ property >
             </ bean >
             < bean
                 class = "org.springframework.http.converter.ResourceHttpMessageConverter" />
             < bean
                 class = "org.springframework.http.converter.xml.SourceHttpMessageConverter" />
             < bean
                 class = "org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter" />
             < bean
                 class = "org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter" />
         </ list >
     </ property >
</ bean >

我们可以从spring日志中看出加这个配置的作用

加之前

[DEBUG] Written [{'err':'',msg:

{'url':'http://localhost:9080/spring/upload/images/2012/11_11/20121111011413.jpg','localname':'我的头

像.jpg','id':'50'}}] as "text/html" using 

[org.springframework.http.converter.StringHttpMessageConverter@93d9c7] 

加之后:
[DEBUG] Written [{'err':'',msg:{'url':'http://localhost:9080/spring/upload/images/2012/11_11/20121111015039.jpg','localname':'我的头像.jpg','id':'63'}}] as "text/plain;charset=UTF-8" using [org.springframework.http.converter.StringHttpMessageConverter@1fdec30]

前台部分,相关的JS如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<script type= "text/javascript" >
     //图片预览
     function previewImage(x){
         $( '#preview' ).attr( "src" , "${ctx}/" + $(x).find( "option:selected" ).val());
     }
     
     $(document).ready( function () {
         //初始化xhEditor编辑器插件 
         $( '#content' ).xheditor({
             tools : 'full' ,
             skin : 'default' ,
             upImgUrl : "${ctx}/upload/image" ,
             upImgExt : "jpg,jpeg,png,gif" ,
             html5Upload : false ,
             onUpload : insertUpload
         });
         
         //图片上传回调函数 
         function insertUpload(arrMsg) {
             //xheditor返回的arrMsg是一个Object数组
             var msg = arrMsg[0];
             
             //(1)其中url插入到编辑器,这样xheditor才能正常显示图片
             var url = msg.url;
             $( "#content" ).append(url);
             //以下步骤不是必须的
             //(2)将attachment_id保存到checkbox中,发表文章时根据这些attachment_id去更新图片的post_id
             var id = msg.id;
             $( "#imagesDiv" ).append( "<input type='checkbox' name='attachments' checked='checked' onclick='return false;' value='" +id+ "''/><br>" );
             
             //(3)图片的名字放到下拉列表,用户从下拉列表 中选择图片做为Post的主题图片
             var localname = msg.localname;
             var urlWithoutHttp = url.substring(url.indexOf( "/upload" )+1);
             $( "#topicImageUrl" ).append( "<option value='" +urlWithoutHttp+ "'>" + localname + "</option>" );
         }
         
         
         //聚焦第一个输入框
         $( "#name" ).focus();
         //为inputForm注册validate函数
         $( "#inputForm" ).validate();
         
     });
</script>

相关的form表单元素如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
< div class = "control-group" >
     < label class = "control-label" for = "content" >内容:</ label >
     < div class = "controls" >
         < sf:textarea path = "content" rows = "15" cssClass = "span10" />
     </ div >
     < div class = "controls" id = "imagesDiv" style = "display:none" >
     </ div >
</ div >
< div class = "control-group" >
     < label class = "control-label" for = "topicImageUrl" >主题图片:</ label >
     < div class = "controls" >
         < sf:select path = "topicImageUrl" onchange = 'previewImage(this)' >
             < sf:option value = "" >Please select</ sf:option >
         </ sf:select >
     </ div >
</ div >
< div class = "control-group" >
     < label class = "control-label" for = "hit" >图片预览:</ label >
     < div class = "controls" >
         < img id = "preview" src = "" border = "0" width = "200" height = "200" />
     </ div >
</ div >

最终的效果如下:


这篇关于spring mvc+xheditor图片上传的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/290547

相关文章

Java+AI驱动实现PDF文件数据提取与解析

《Java+AI驱动实现PDF文件数据提取与解析》本文将和大家分享一套基于AI的体检报告智能评估方案,详细介绍从PDF上传、内容提取到AI分析、数据存储的全流程自动化实现方法,感兴趣的可以了解下... 目录一、核心流程:从上传到评估的完整链路二、第一步:解析 PDF,提取体检报告内容1. 引入依赖2. 封装

使用Spring Cache本地缓存示例代码

《使用SpringCache本地缓存示例代码》缓存是提高应用程序性能的重要手段,通过将频繁访问的数据存储在内存中,可以减少数据库访问次数,从而加速数据读取,:本文主要介绍使用SpringCac... 目录一、Spring Cache简介核心特点:二、基础配置1. 添加依赖2. 启用缓存3. 缓存配置方案方案

Java实现复杂查询优化的7个技巧小结

《Java实现复杂查询优化的7个技巧小结》在Java项目中,复杂查询是开发者面临的“硬骨头”,本文将通过7个实战技巧,结合代码示例和性能对比,手把手教你如何让复杂查询变得优雅,大家可以根据需求进行选择... 目录一、复杂查询的痛点:为何你的代码“又臭又长”1.1冗余变量与中间状态1.2重复查询与性能陷阱1.

深度剖析SpringBoot日志性能提升的原因与解决

《深度剖析SpringBoot日志性能提升的原因与解决》日志记录本该是辅助工具,却为何成了性能瓶颈,SpringBoot如何用代码彻底破解日志导致的高延迟问题,感兴趣的小伙伴可以跟随小编一起学习一下... 目录前言第一章:日志性能陷阱的底层原理1.1 日志级别的“双刃剑”效应1.2 同步日志的“吞吐量杀手”

Spring创建Bean的八种主要方式详解

《Spring创建Bean的八种主要方式详解》Spring(尤其是SpringBoot)提供了多种方式来让容器创建和管理Bean,@Component、@Configuration+@Bean、@En... 目录引言一、Spring 创建 Bean 的 8 种主要方式1. @Component 及其衍生注解

SpringBoot通过main方法启动web项目实践

《SpringBoot通过main方法启动web项目实践》SpringBoot通过SpringApplication.run()启动Web项目,自动推断应用类型,加载初始化器与监听器,配置Spring... 目录1. 启动入口:SpringApplication.run()2. SpringApplicat

Java利用@SneakyThrows注解提升异常处理效率详解

《Java利用@SneakyThrows注解提升异常处理效率详解》这篇文章将深度剖析@SneakyThrows的原理,用法,适用场景以及隐藏的陷阱,看看它如何让Java异常处理效率飙升50%,感兴趣的... 目录前言一、检查型异常的“诅咒”:为什么Java开发者讨厌它1.1 检查型异常的痛点1.2 为什么说

基于Java开发一个极简版敏感词检测工具

《基于Java开发一个极简版敏感词检测工具》这篇文章主要为大家详细介绍了如何基于Java开发一个极简版敏感词检测工具,文中的示例代码简洁易懂,感兴趣的小伙伴可以跟随小编一起学习一下... 目录你是否还在为敏感词检测头疼一、极简版Java敏感词检测工具的3大核心优势1.1 优势1:DFA算法驱动,效率提升10

Java使用正则提取字符串中的内容的详细步骤

《Java使用正则提取字符串中的内容的详细步骤》:本文主要介绍Java中使用正则表达式提取字符串内容的方法,通过Pattern和Matcher类实现,涵盖编译正则、查找匹配、分组捕获、数字与邮箱提... 目录1. 基础流程2. 关键方法说明3. 常见场景示例场景1:提取所有数字场景2:提取邮箱地址4. 高级

使用SpringBoot+InfluxDB实现高效数据存储与查询

《使用SpringBoot+InfluxDB实现高效数据存储与查询》InfluxDB是一个开源的时间序列数据库,特别适合处理带有时间戳的监控数据、指标数据等,下面详细介绍如何在SpringBoot项目... 目录1、项目介绍2、 InfluxDB 介绍3、Spring Boot 配置 InfluxDB4、I