kindEditor文件上传

2024-05-26 02:18
文章标签 上传 kindeditor

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


public class KindeditorController {


// 定义允许上传的文件扩展名
private static Map<String, String> extMap = new HashMap<String, String>();
static {
extMap.put("image", "gif,jpg,jpeg,png,bmp");
extMap.put("flash", "swf,flv");
extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");
}


// 最大文件大小
long maxSize = 1000000;


@RequestMapping("editor")
public String kindEditor() {
return "kindEditor";
}


/*
* 文件上传

* @param request

* @param response

* @return

* @throws FileUploadException

* @throws IOException 2013-10-11
*/
@ResponseBody
@RequestMapping("uploadJson")
public Map<String, Object> uploadJson(HttpServletRequest request, HttpServletResponse response)
throws FileUploadException, IOException {
response.setContentType("text/html; charset=UTF-8");

Map<String, Object> result = Maps.newHashMap();


// 文件保存目录路径
String savePath = this.getSysPath();


if (!ServletFileUpload.isMultipartContent(request)) {
result.put("message", "请选择文件.");
return result;
}
// 检查目录
File uploadDir = new File(savePath);
if (!uploadDir.isDirectory()) {
result.put("message", "上传目录不存在.");
return result;
}
// 检查目录写权限
if (!uploadDir.canWrite()) {
result.put("message", "上传目录没有写权限.");
return result;
}


String dirName = request.getParameter("dir");
if (dirName == null) {
dirName = "image";
}
if (!extMap.containsKey(dirName)) {
result.put("message", "请选择其他格式文件上传.");
return result;
}
// 创建文件夹
savePath += dirName + "/";
File saveDirFile = new File(savePath);
if (!saveDirFile.exists()) {
saveDirFile.mkdirs();
}
try {
// 设置上下方文
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request
.getSession().getServletContext());


// 检查form是否有enctype="multipart/form-data"
if (multipartResolver.isMultipart(request)) {
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;


Iterator<String> iter = multiRequest.getFileNames();
while (iter.hasNext()) {


// 由CommonsMultipartFile继承而来,拥有上面的方法.
MultipartFile file = multiRequest.getFile(iter.next());
if (file != null) {
// 检查文件大小
if (file.getSize() > maxSize) {
result.put("message", "上传文件大小超过限制.");
return result;
} else {
// 检查扩展名
String fileName = file.getOriginalFilename();
String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1)
.toLowerCase();
if (!Arrays.<String> asList(extMap.get(dirName).split(",")).contains(
fileExt)) {
result.put("message",
"上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式.");
return result;
} else {
try {
File uploadedFile = new File(savePath, fileName);
file.transferTo(uploadedFile);
result.put("message", "上传成功.");
} catch (Exception e) {
result.put("message", "上传文件失败.");
return result;
}
}


}
}
}
} else {
result.put("message", "上传失败.");
return result;
}
} catch (Exception e) {
result.put("message", "上传失败.");
return result;
}
return result;
}


 
/*
* 获取根目录

* @return 2013-10-12
*/
private String getSysPath() {
String sysPath = KindeditorController.class.getResource("/").getPath();
String str = sysPath.substring(0, sysPath.length() - 1);
String savePath = str.substring(0, str.lastIndexOf("/") - 6)
+ "attached/";
return savePath;
}


/*
* 文件管理

* @param request

* @param response

* @return

* @throws IOException 2013-10-11
*/
@ResponseBody
@RequestMapping(value = "fileManagerJson")
public String fileManagerJson(HttpServletRequest request, HttpServletResponse response)
throws IOException {
// 根目录路径
String rootPath = this.getSysPath();


// 根目录URL
String rootUrl = request.getContextPath()+"/src/main/webapp/static/attached/";
// 图片扩展名
String[] fileTypes = new String[] { "gif", "jpg", "jpeg", "png", "bmp" };


String dirName = request.getParameter("dir");
Map<String, Object> result = Maps.newHashMap();
if (dirName != null) {
if (!Arrays.<String> asList(new String[] { "image", "flash", "media", "file" })
.contains(dirName)) {
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) {
return "不允许此类访问方式.";
}
// 最后一个字符不是/
if (!"".equals(path) && !path.endsWith("/")) {
return "参数无效.";
}
// 目录不存在或不是目录
File currentPathFile = new File(currentPath);
if (!currentPathFile.isDirectory()) {
return "目录不存在.";
}


// 遍历目录取的文件信息
@SuppressWarnings("rawtypes")
List<Hashtable> fileList = Lists.newArrayList();
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 { //"name".equals(order)
Collections.sort(fileList, new NameComparator());
}
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");
return JsonMapper.alwaysMapper().toJson(result);
}


/*
* 根据文件名称排序
*/
public class NameComparator implements Comparator<Object> {
public int compare(Object a, Object b) {
@SuppressWarnings("rawtypes")
Hashtable hashA = (Hashtable) a;
@SuppressWarnings("rawtypes")
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<Object> {
public int compare(Object a, Object b) {
@SuppressWarnings("rawtypes")
Hashtable hashA = (Hashtable) a;
@SuppressWarnings("rawtypes")
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<Object> {
public int compare(Object a, Object b) {
@SuppressWarnings("rawtypes")
Hashtable hashA = (Hashtable) a;
@SuppressWarnings("rawtypes")
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"));
}
}
}
 
}

这篇关于kindEditor文件上传的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

使用Node.js制作图片上传服务的详细教程

《使用Node.js制作图片上传服务的详细教程》在现代Web应用开发中,图片上传是一项常见且重要的功能,借助Node.js强大的生态系统,我们可以轻松搭建高效的图片上传服务,本文将深入探讨如何使用No... 目录准备工作搭建 Express 服务器配置 multer 进行图片上传处理图片上传请求完整代码示例

Java实现数据库图片上传与存储功能

《Java实现数据库图片上传与存储功能》在现代的Web开发中,上传图片并将其存储在数据库中是常见的需求之一,本文将介绍如何通过Java实现图片上传,存储到数据库的完整过程,希望对大家有所帮助... 目录1. 项目结构2. 数据库表设计3. 实现图片上传功能3.1 文件上传控制器3.2 图片上传服务4. 实现

使用mvn deploy命令上传jar包的实现

《使用mvndeploy命令上传jar包的实现》本文介绍了使用mvndeploy:deploy-file命令将本地仓库中的JAR包重新发布到Maven私服,文中通过示例代码介绍的非常详细,对大家的学... 目录一、背景二、环境三、配置nexus上传账号四、执行deploy命令上传包1. 首先需要把本地仓中要

Java实现数据库图片上传功能详解

《Java实现数据库图片上传功能详解》这篇文章主要为大家详细介绍了如何使用Java实现数据库图片上传功能,包含从数据库拿图片传递前端渲染,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1、前言2、数据库搭建&nbsChina编程p; 3、后端实现将图片存储进数据库4、后端实现从数据库取出图片给前端5、前端拿到

Vue ElementUI中Upload组件批量上传的实现代码

《VueElementUI中Upload组件批量上传的实现代码》ElementUI中Upload组件批量上传通过获取upload组件的DOM、文件、上传地址和数据,封装uploadFiles方法,使... ElementUI中Upload组件如何批量上传首先就是upload组件 <el-upl

Java文件上传的多种实现方式

《Java文件上传的多种实现方式》文章主要介绍了文件上传接收接口的使用方法,包括获取文件信息、创建文件夹、保存文件到本地的两种方法,以及如何使用Postman进行接口调用... 目录Java文件上传的多方式1.文件上传接收文件接口2.接口主要内容部分3.postman接口调用总结Java文件上传的多方式1

使用Python实现大文件切片上传及断点续传的方法

《使用Python实现大文件切片上传及断点续传的方法》本文介绍了使用Python实现大文件切片上传及断点续传的方法,包括功能模块划分(获取上传文件接口状态、临时文件夹状态信息、切片上传、切片合并)、整... 目录概要整体架构流程技术细节获取上传文件状态接口获取临时文件夹状态信息接口切片上传功能文件合并功能小

Spring MVC 图片上传

引入需要的包 <dependency><groupId>commons-logging</groupId><artifactId>commons-logging</artifactId><version>1.1</version></dependency><dependency><groupId>commons-io</groupId><artifactId>commons-

在SSH的基础上使用jquery.uploadify.js上传文件

在SSH框架的基础上,使用jquery.uploadify.js实现文件的上传,之前搞了好几天,都上传不了, 在Action那边File接收到的总是为null, 为了这个还上网搜了好多相关的信息,但都不行,最后还是搜到一篇文章帮助到我了,希望能帮助到为之困扰的人。 jsp页面的关键代码: <link rel="stylesheet" type="text/css" href="${page

【CTF Web】BUUCTF Upload-Labs-Linux Pass-13 Writeup(文件上传+PHP+文件包含漏洞+PNG图片马)

Upload-Labs-Linux 1 点击部署靶机。 简介 upload-labs是一个使用php语言编写的,专门收集渗透测试和CTF中遇到的各种上传漏洞的靶场。旨在帮助大家对上传漏洞有一个全面的了解。目前一共20关,每一关都包含着不同上传方式。 注意 1.每一关没有固定的通关方法,大家不要自限思维! 2.本项目提供的writeup只是起一个参考作用,希望大家可以分享出自己的通关思路