服务器之家

服务器之家 > 正文

springmvc+kindeditor文件上传实例详解

时间:2021-05-28 13:41     来源/作者:華leo

本文实例为大家分享了springmvc+kindeditor文件上传的具体代码,供大家参考,具体内容如下

下载kindeditor

压缩包里面的jar放到tomcat的lib文件夹下,kindeditor文件放工程里,不用的可以删掉

springmvc+kindeditor文件上传实例详解

jsp页面

?
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
<%@ page language="java" contenttype="text/html; charset=utf-8"
 pageencoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd">
<html>
<link rel="stylesheet"
 href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="external nofollow" >
<script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script>
<script
 src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="./kindeditor/kindeditor-all-min.js"></script>
<script src="./kindeditor/lang/zh-cn.js"></script>
<script>
 kindeditor
   .ready(function(k) {
    window.editor = k
      .create(
        '#editor_id',
        {
         uploadjson : 'kindeditor/uploadfile',
         filemanagerjson : 'kindeditor/filemanager',
         allowimageupload : true, //多图上传
         allowfilemanager : true, //浏览图片空间
         filtermode : false, //html特殊代码过滤
         afterblur : function() {
          this.sync();
         }, //编辑器失去焦点(blur)时执行的回调函数(将编辑器的html数据同步到textarea)
         afterupload : function(url, data, name) { //上传文件后执行的回调函数,必须为3个参数
          if (name == "image"
            || name == "multiimage") { //单个和批量上传图片时
           if (k("#pic").length > 0) { //文本框存在
            document
              .getelementbyid('piclist').options[document
              .getelementbyid('piclist').length] = new option(
              url, url); //下拉列表框增加一条
            document
              .getelementbyid('piclist').selectedindex += 1; //选定刚新增的这一条
            k("#indexpicimg")
              .html(
                "<img src='" + url + "' width='150' height='95' />"); //重置图片展示区div的html内容
            k("#pic").val(url); //重置文本框值
           }
          }
         }
        });
   });
</script>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>insert title here</title>
</head>
<body>
 <form class="form-horizontal" role="form" action="articleadd" method="post" >
  <div class="form-group">
   <label for="firstname" class="col-sm-2 control-label">标题</label>
   <div class="col-sm-5">
    <input type="text" class="form-control" id="title" name="title"
     placeholder="请输入标题">
   </div>
  </div>
  <div class="form-group">
   <label for="lastname" class="col-sm-2 control-label">类别</label>
   <div class="col-sm-3">
    <select class="form-control" name="categoryid">
     <option>1</option>
     <option>2</option>
     <option>3</option>
     <option>4</option>
     <option>5</option>
    </select>
   </div>
  </div>
  <div class="form-group">
   <label for="lastname" class="col-sm-2 control-label">内容</label>
   <div class=" col-sm-5">
    <textarea id="editor_id" name="details"
     class="form-control" >
    <strong>html内容</strong>
    </textarea>
   </div>
  </div>
  <div class="form-group">
   <div class="col-sm-offset-2 col-sm-10">
    <button type="submit" class="btn btn-default">保存草稿</button>
   </div>
  </div>
 </form>
 
</body>
</html>

kindaction.java

?
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
package com.leo.ows.action;
 
import java.io.bufferedoutputstream;
import java.io.file;
import java.io.fileoutputstream;
import java.io.printwriter;
import java.text.simpledateformat;
import java.util.arraylist;
import java.util.arrays;
import java.util.collections;
import java.util.comparator;
import java.util.hashmap;
import java.util.hashtable;
import java.util.iterator;
import java.util.list;
import java.util.map;
import java.util.uuid;
 
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
import org.apache.commons.fileupload.servlet.servletfileupload;
import org.springframework.stereotype.controller;
import org.springframework.util.filecopyutils;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.requestmethod;
import org.springframework.web.multipart.multipartfile;
import org.springframework.web.multipart.multiparthttpservletrequest;
 
import com.alibaba.fastjson.jsonobject;
@controller
public class kindaction {
 
 @requestmapping(value ="/kindeditor/uploadfile", method = requestmethod.post)
 public void uploadfile(httpservletrequest request, httpservletresponse response) throws exception {
  printwriter writer = response.getwriter();
  // 文件保存目录路径
  string savepath = request.getsession().getservletcontext().getrealpath("/") + "upload/image" + file.separatorchar
     + file.separatorchar;
 
  string saveurl = request.getcontextpath()+ file.separatorchar + "upload/image" + file.separatorchar
    + file.separatorchar;
 
  // 定义允许上传的文件扩展名
  hashmap<string, string> extmap = new hashmap<string, string>();
  extmap.put("image", "gif,jpg,jpeg,png,bmp");
 
  // 最大文件大小
  long maxsize = 1000000;
  response.setcontenttype("text/html; charset=utf-8");
 
  if (!servletfileupload.ismultipartcontent(request)) {
   writer.println(geterror("请选择文件。"));
   return;
  }
 
  file uploaddir = new file(savepath);
  // 判断文件夹是否存在,如果不存在则创建文件夹
  if (!uploaddir.exists()) {
   uploaddir.mkdirs();
  }
 
  // 检查目录写权限
  if (!uploaddir.canwrite()) {
   writer.println(geterror("上传目录没有写权限。"));
   return;
  }
 
  string dirname = request.getparameter("dir");
  if (dirname == null) {
   dirname = "image";
  }
  if (!extmap.containskey(dirname)) {
   writer.println(geterror("目录名不正确。"));
   return;
  }
 
  multiparthttpservletrequest mrequest = (multiparthttpservletrequest) request;
  map<string, multipartfile> filemap = mrequest.getfilemap();
  string filename = null;
  for (iterator<map.entry<string, multipartfile>> it = filemap.entryset().iterator(); it.hasnext();) {
   map.entry<string, multipartfile> entry = it.next();
   multipartfile mfile = entry.getvalue();
   filename = mfile.getoriginalfilename();
   // 检查文件大小
   if (mfile.getsize() > maxsize) {
    writer.println(geterror("上传文件大小超过限制。"));
    return;
   }
   string fileext = filename.substring(filename.lastindexof(".")+1);
   if (!arrays.<string> aslist(extmap.get(dirname).split(",")).contains(fileext)) {
    writer.println(geterror("上传文件扩展名是不允许的扩展名。\n只允许" + extmap.get(dirname) + "格式。"));
    return;
   }
   uuid uuid = uuid.randomuuid();
   string path = savepath + uuid.tostring() +"."+ fileext;
   saveurl = saveurl + uuid.tostring() +"."+ fileext;
   bufferedoutputstream outputstream = new bufferedoutputstream(new fileoutputstream(path));
   filecopyutils.copy(mfile.getinputstream(), outputstream);
 
   jsonobject obj = new jsonobject();
   obj.put("error", 0);
   obj.put("url", saveurl);
   writer.println(obj.tostring());
 
  }
 }
 
 
 private string geterror(string message) {
  jsonobject obj = new jsonobject();
  obj.put("error", 1);
  obj.put("message", message);
  return obj.tostring();
 }
 
 @requestmapping(value = "/kindeditor/filemanager", method = requestmethod.get)
 public void filemanager(httpservletrequest request, httpservletresponse response) throws exception {
  //根目录路径,可以指定绝对路径,比如 /var/www/attached/
  string rootpath = request.getsession().getservletcontext().getrealpath("/")+ "upload/";
  //根目录url,可以指定绝对路径,比如 http://www.yoursite.com/attached/
  string rooturl = request.getcontextpath() + "/upload/";
  //图片扩展名
  string[] filetypes = new string[]{"gif", "jpg", "jpeg", "png", "bmp"};
  system.out.println(rootpath);
  string dirname = request.getparameter("dir");
  if (dirname != null) {
   if(!arrays.<string>aslist(new string[]{"image", "flash", "media", "file"}).contains(dirname)){
    system.out.println("invalid directory name.");
    return;
   }
   rootpath += dirname + "/";
   rooturl += dirname + "/";
   file savedirfile = new file(rootpath);
   if (!savedirfile.exists()) {
    savedirfile.mkdirs();
   }
  }
  //根据path参数,设置各路径和url
  string path = request.getparameter("path") != null ? request.getparameter("path") : "";
  string currentpath = rootpath + path;
  string currenturl = rooturl + path;
  string currentdirpath = path;
  string moveupdirpath = "";
  if (!"".equals(path)) {
   string str = currentdirpath.substring(0, currentdirpath.length() - 1);
   moveupdirpath = str.lastindexof("/") >= 0 ? str.substring(0, str.lastindexof("/") + 1) : "";
  }
 
  //排序形式,name or size or type
  string order = request.getparameter("order") != null ? request.getparameter("order").tolowercase() : "name";
 
  //不允许使用..移动到上一级目录
  if (path.indexof("..") >= 0) {
   system.out.println("access is not allowed.");
   return;
  }
  //最后一个字符不是/
  if (!"".equals(path) && !path.endswith("/")) {
   system.out.println("parameter is not valid.");
   return;
  }
  //目录不存在或不是目录
  file currentpathfile = new file(currentpath);
  if(!currentpathfile.isdirectory()){
   system.out.println("directory does not exist.");
   return;
  }
 
  //遍历目录取的文件信息
  list<hashtable> filelist = new arraylist<hashtable>();
  if(currentpathfile.listfiles() != null) {
   for (file file : currentpathfile.listfiles()) {
    hashtable<string, object> hash = new hashtable<string, object>();
    string filename = file.getname();
    if(file.isdirectory()) {
     hash.put("is_dir", true);
     hash.put("has_file", (file.listfiles() != null));
     hash.put("filesize", 0l);
     hash.put("is_photo", false);
     hash.put("filetype", "");
    } else if(file.isfile()){
     string fileext = filename.substring(filename.lastindexof(".") + 1).tolowercase();
     hash.put("is_dir", false);
     hash.put("has_file", false);
     hash.put("filesize", file.length());
     hash.put("is_photo", arrays.<string>aslist(filetypes).contains(fileext));
     hash.put("filetype", fileext);
    }
    hash.put("filename", filename);
    hash.put("datetime", new simpledateformat("yyyy-mm-dd hh:mm:ss").format(file.lastmodified()));
    filelist.add(hash);
   }
  }
 
  if ("size".equals(order)) {
   collections.sort(filelist, new sizecomparator());
  } else if ("type".equals(order)) {
   collections.sort(filelist, new typecomparator());
  } else {
   collections.sort(filelist, new namecomparator());
  }
  jsonobject result = new jsonobject();
  result.put("moveup_dir_path", moveupdirpath);
  result.put("current_dir_path", currentdirpath);
  result.put("current_url", currenturl);
  result.put("total_count", filelist.size());
  result.put("file_list", filelist);
  response.setcontenttype("application/json; charset=utf-8");
  system.out.println(result.tojsonstring());
  printwriter writer=response.getwriter();
  writer.println(result);
 }
 
 
 public class namecomparator implements comparator {
  public int compare(object a, object b) {
   hashtable hasha = (hashtable)a;
   hashtable hashb = (hashtable)b;
   if (((boolean)hasha.get("is_dir")) && !((boolean)hashb.get("is_dir"))) {
    return -1;
   } else if (!((boolean)hasha.get("is_dir")) && ((boolean)hashb.get("is_dir"))) {
    return 1;
   } else {
    return ((string)hasha.get("filename")).compareto((string)hashb.get("filename"));
   }
  }
 }
 public class sizecomparator implements comparator {
  public int compare(object a, object b) {
   hashtable hasha = (hashtable)a;
   hashtable hashb = (hashtable)b;
   if (((boolean)hasha.get("is_dir")) && !((boolean)hashb.get("is_dir"))) {
    return -1;
   } else if (!((boolean)hasha.get("is_dir")) && ((boolean)hashb.get("is_dir"))) {
    return 1;
   } else {
    if (((long)hasha.get("filesize")) > ((long)hashb.get("filesize"))) {
     return 1;
    } else if (((long)hasha.get("filesize")) < ((long)hashb.get("filesize"))) {
     return -1;
    } else {
     return 0;
    }
   }
  }
 }
 public class typecomparator implements comparator {
  public int compare(object a, object b) {
   hashtable hasha = (hashtable)a;
   hashtable hashb = (hashtable)b;
   if (((boolean)hasha.get("is_dir")) && !((boolean)hashb.get("is_dir"))) {
    return -1;
   } else if (!((boolean)hasha.get("is_dir")) && ((boolean)hashb.get("is_dir"))) {
    return 1;
   } else {
    return ((string)hasha.get("filetype")).compareto((string)hashb.get("filetype"));
   }
  }
 }
 
}

效果图

springmvc+kindeditor文件上传实例详解

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/shihua0610/article/details/77183262

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
2021德云社封箱演出完整版 2021年德云社封箱演出在线看
2021德云社封箱演出完整版 2021年德云社封箱演出在线看 2021-03-15
返回顶部