kindEditor文件上传

来源:互联网 发布:康师傅免流量软件 编辑:程序博客网 时间:2024/06/06 03:24
  
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"));
}
}
}
 
}
原创粉丝点击