激情久久久_欧美视频区_成人av免费_不卡视频一二三区_欧美精品在欧美一区二区少妇_欧美一区二区三区的

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - Java教程 - springmvc+kindeditor文件上傳實例詳解

springmvc+kindeditor文件上傳實例詳解

2021-05-28 13:41華leo Java教程

這篇文章主要為大家詳細介紹了springmvc+kindeditor文件上傳實例,具有一定的參考價值,感興趣的小伙伴們可以參考一下

本文實例為大家分享了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

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: jizzjizz中国少妇中文 | av免费不卡国产观看 | 加勒比婷婷色综合久久 | 国产毛片网站 | av国产片 | 成人羞羞视频在线观看免费 | 91精品国产九九九久久久亚洲 | 国产一级淫片a级aaa | 日美av在线 | 视频一区二区中文字幕 | 成人毛片免费播放 | 欧美顶级毛片在线播放小说 | 国产精品一区二区三区在线播放 | 欧美成人免费 | 欧美三日本三级少妇三级99观看视频 | 成人在线观看一区二区 | 国产毛毛片一区二区三区四区 | 热@国产 | 色播视频在线播放 | 欧美一级一区二区三区 | 国产亚洲欧美日韩在线观看不卡 | 91一区二区在线观看 | 婷婷久久久久久 | 久久99国产精品视频 | 欧美亚成人 | 欧美久久一区 | 依人在线视频 | 欧美亚洲免费 | 欧美一级成人 | 欧美日韩国产成人在线观看 | 九九热播视频 | 日本在线播放一区二区三区 | www.狠狠插.com| 欧美成人鲁丝片在线观看 | 日产精品久久久一区二区福利 | 国产精品热 | 免费黄色在线电影 | 97中文| 网站激情 | av在线免费观看不卡 | 国产91九色视频 |