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 >

最终的效果如下:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
xheditor是一款富文本编辑器,用于网页开发中的文本编辑功能。然而,xheditor也存在一些漏洞,以下是一些常见的漏洞: 1. XSS(跨站脚本攻击)漏洞:xheditor对于输入内容的过滤不够严格,导致攻击者可以在编辑器中插入恶意脚本代码,进而窃取用户的敏感信息。这可以通过在输入内容中嵌入<script>标签或其他能执行脚本的代码来实现。 2. 文件上漏洞:xheditor允许用户上文件,但在文件上的过程中,未进行足够的文件类型和大小验证,这可能导致恶意文件上和执行。攻击者可以上包含恶意脚本的文件或者超过系统承载能力的大文件,造成拒绝服务或其他安全风险。 3. 未经授权的访问漏洞:xheditor在默认情况下没有使用身份验证和授权措施,这使得未授权的用户可以直接访问和使用编辑器功能。攻击者可以在没有权限的情况下修改、删除或发布内容,这对网站的安全和数据完整性构成威胁。 针对xheditor的这些漏洞,建议采取以下措施来改进安全性: 1. 对用户输入内容进行严格的过滤和验证,防止XSS攻击。可以使用HTML转义或过滤器来去除或替换输入中的危险字符和标签。 2. 在文件上过程中,限制文件类型和大小,并进行正确的文件检查和处理。可以采用白名单验证,只允许上安全的文件类型,并设置最大文件上限制,以防止恶意文件上和执行。 3. 添加身份验证和授权机制,限制对xheditor的访问权限。只有经过授权的用户才能使用编辑器功能,避免未授权用户对内容进行修改或发布。 4. 定期更新和维护xheditor,及时修复已知的漏洞。保持软件的最新版本,并及时关注安全社区的公告和建议,确保及时应对新出现的漏洞。 总之,xheditor作为一款常用的富文本编辑器,需要开发人员在使用时注意其潜在的漏洞,并采取相应的安全措施,以保护网站和用户的安全。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值