当前位置: 移动技术网 > IT编程>开发语言>Java > springmvc+kindeditor文件上传实例详解

springmvc+kindeditor文件上传实例详解

2019年07月19日  | 移动技术网IT编程  | 我要评论
本文实例为大家分享了springmvc+kindeditor文件上传的具体代码,供大家参考,具体内容如下 下载 压缩包里面的jar放到tomcat的lib文件夹下,ki

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

下载

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

jsp页面

<%@ 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

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"));
   }
  }
 }

}

效果图

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网