SpringMVC KindEditor在線編輯器之文件上傳代碼實(shí)例
最近幾個(gè)項(xiàng)目都要用到在線編輯器,由于之前做在線編輯器都只在php上,對(duì)于用java尤其是springmvc框架時(shí),似乎并不如PHP那么簡(jiǎn)單,搜集了很多博文和資料,全部都不能達(dá)到效果,最后在參考各種資料后,自己花時(shí)間寫了一個(gè)上傳圖片的控制器,親測(cè)保證能用。
1.圖片上傳控制器
package com.xishan.yueke.view.system;
import java.io.File;
import java.io.IOException;
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.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.json.simple.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.xishan.yueke.view.BaseAction;
/**
* Class Name: FileManageAction.java
* Function:
* 在線編輯器控制器
* @author Yang Ji.
* @DateTime 2015年8月10日 下午8:26:50
* @version 1.0
*/
@Controller
public class FileManageAction extends BaseAction
{
// windows
// private String PATH_LINE = "\\";
// linux
private String PATH_LINE = "/";
/**
* 文件上傳
* @param request {@link HttpServletRequest}
* @param response {@link HttpServletResponse}
* @return json response
*/
@SuppressWarnings("unchecked")
@RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
@ResponseBody
public void fileUpload(HttpServletRequest request,
HttpServletResponse response,
@RequestParam("imgFile") MultipartFile[] imgFile) {
try {
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
//文件保存本地目錄路徑
String savePath = request.getSession().getServletContext().getRealPath(PATH_LINE) + "kindeditor"+PATH_LINE+"attached"+PATH_LINE;
//文件保存目錄URL
String saveUrl = request.getContextPath() + PATH_LINE +"kindeditor"+PATH_LINE+"attached"+PATH_LINE;
if(!ServletFileUpload.isMultipartContent(request)){
out.print(getError("請(qǐng)選擇文件。"));
out.close();
return;
}
//檢查目錄
File uploadDir = new File(savePath);
if(!uploadDir.isDirectory()){
out.print(getError("上傳目錄不存在。"));
out.close();
return;
}
//檢查目錄寫權(quán)限
if(!uploadDir.canWrite()){
out.print(getError("上傳目錄沒有寫權(quán)限。"));
out.close();
return;
}
String dirName = request.getParameter("dir");
if (dirName == null) {
dirName = "image";
}
//定義允許上傳的文件擴(kuò)展名
Map<String, String> extMap = new HashMap<String, String>();
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,xml,txt,zip,rar,gz,bz2");
if(!extMap.containsKey(dirName)){
out.print(getError("目錄名不正確。"));
out.close();
return;
}
//創(chuàng)建文件夾
savePath += dirName + PATH_LINE;
saveUrl += dirName + PATH_LINE;
File saveDirFile = new File(savePath);
if (!saveDirFile.exists()) {
saveDirFile.mkdirs();
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String ymd = sdf.format(new Date());
savePath += ymd + PATH_LINE;
saveUrl += ymd + PATH_LINE;
File dirFile = new File(savePath);
if (!dirFile.exists()) {
dirFile.mkdirs();
}
//最大文件大小
long maxSize = 1000000;
// 保存文件
for(MultipartFile iFile : imgFile){
String fileName = iFile.getOriginalFilename();
//檢查文件大小
if(iFile.getSize() > maxSize){
out.print(getError("上傳文件大小超過限制。"));
out.close();
return;
}
//檢查擴(kuò)展名
String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
if(!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)){
//return getError("上傳文件擴(kuò)展名是不允許的擴(kuò)展名。\n只允許" + extMap.get(dirName) + "格式。");
out.print(getError("上傳文件擴(kuò)展名是不允許的擴(kuò)展名。\n只允許" + extMap.get(dirName) + "格式。"));
out.close();
return;
}
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
try{
File uploadedFile = new File(savePath, newFileName);
// 寫入文件
FileUtils.copyInputStreamToFile(iFile.getInputStream(), uploadedFile);
}catch(Exception e){
out.print(getError("上傳文件失敗。"));
out.close();
return;
}
JSONObject obj = new JSONObject();
obj.put("error", 0);
obj.put("url", saveUrl + newFileName);
out.print(obj.toJSONString());
out.close();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private Map<String, Object> getError(String errorMsg) {
Map<String, Object> errorMap = new HashMap<String, Object>();
errorMap.put("error", 1);
errorMap.put("message", errorMsg);
return errorMap;
}
/**
* 文件空間
* @param request {@link HttpServletRequest}
* @param response {@link HttpServletResponse}
* @return json
*/
@SuppressWarnings("unchecked")
@RequestMapping(value = "/fileManager")
@ResponseBody
public void fileManager(HttpServletRequest request, HttpServletResponse response) {
try {
//根目錄路徑,可以指定絕對(duì)路徑
String rootPath = request.getSession().getServletContext().getRealPath(PATH_LINE) + "kindeditor"+PATH_LINE+"attached"+PATH_LINE;
//根目錄URL,可以指定絕對(duì)路徑,比如 http://www.yoursite.com/attached/
String rootUrl = request.getContextPath() + PATH_LINE+"kindeditor"+PATH_LINE+"attached"+PATH_LINE;
response.setContentType("application/json; charset=UTF-8");
PrintWriter out = response.getWriter();
//圖片擴(kuò)展名
String[] fileTypes = new String[]{"gif", "jpg", "jpeg", "png", "bmp"};
String dirName = request.getParameter("dir");
if (dirName != null) {
if(!Arrays.<String>asList(new String[]{"image", "flash", "media", "file"}).contains(dirName)){
out.print("無效的文件夾。");
out.close();
return;
}
rootPath += dirName + PATH_LINE;
rootUrl += dirName + PATH_LINE;
File saveDirFile = new File(rootPath);
if (!saveDirFile.exists()) {
saveDirFile.mkdirs();
}
}
//根據(jù)path參數(shù),設(shè)置各路徑和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(PATH_LINE) >= 0 ? str.substring(0, str.lastIndexOf(PATH_LINE) + 1) : "";
}
//排序形式,name or size or type
String order = request.getParameter("order") != null ? request.getParameter("order").toLowerCase() : "name";
//不允許使用..移動(dòng)到上一級(jí)目錄
if (path.indexOf("..") >= 0) {
out.print("訪問權(quán)限拒絕。");
out.close();
return;
}
//最后一個(gè)字符不是/
if (!"".equals(path) && !path.endsWith(PATH_LINE)) {
out.print("無效的訪問參數(shù)驗(yàn)證。");
out.close();
return;
}
//目錄不存在或不是目錄
File currentPathFile = new File(currentPath);
if(!currentPathFile.isDirectory()){
out.print("文件夾不存在。");
out.close();
return;
}
//遍歷目錄取的文件信息
List<Map<String, Object>> fileList = new ArrayList<Map<String, Object>>();
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);
out.println(result.toJSONString());
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private class NameComparator implements Comparator<Map<String, Object>> {
public int compare(Map<String, Object> hashA, Map<String, Object> hashB) {
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"));
}
}
}
private class SizeComparator implements Comparator<Map<String, Object>> {
public int compare(Map<String, Object> hashA, Map<String, Object> hashB) {
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;
}
}
}
}
private class TypeComparator implements Comparator<Map<String, Object>> {
public int compare(Map<String, Object> hashA, Map<String, Object> hashB) {
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"));
}
}
}
}
2.jsp頁面使用方法(在head加入下面代碼,替換名為description的編輯區(qū),在此之前需導(dǎo)入kindeditor的相關(guān)文件,詳見官方文檔)
<script type="text/javascript">
KindEditor.ready(function(K) {
K.create('textarea[name="descript"]', {
uploadJson : 'http://localhost:8080/Test/fileUpload.htm',
fileManagerJson : 'http://localhost:8080/Test/fileManager.htm',
allowFileManager : true,
allowImageUpload : true,
autoHeightMode : true,
width : "640px",
height : "400px",
afterCreate : function() {this.loadPlugin('autoheight');},
afterBlur : function(){ this.sync(); } //Kindeditor下獲取文本框信息
});
});
</script>
使用其他的框架(比如Spring+Struts+Hibernate)方法大致相同,最終效果如下:

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
spring事務(wù)之事務(wù)掛起和事務(wù)恢復(fù)源碼解讀
這篇文章主要介紹了spring事務(wù)之事務(wù)掛起和事務(wù)恢復(fù)源碼解讀,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-11-11
mybatisplus報(bào)Invalid bound statement (not found)錯(cuò)誤的解決方法
搭建項(xiàng)目時(shí)使用了mybatisplus,項(xiàng)目能夠正常啟動(dòng),但在調(diào)用mapper方法查詢數(shù)據(jù)庫(kù)時(shí)報(bào)Invalid bound statement (not found)錯(cuò)誤。本文給大家分享解決方案,感興趣的朋友跟隨小編一起看看吧2020-08-08
Spring?main方法中如何調(diào)用Dao層和Service層的方法
這篇文章主要介紹了Spring?main方法中調(diào)用Dao層和Service層的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-12-12
Spring中的FactoryBean實(shí)現(xiàn)原理詳解
這篇文章主要介紹了Spring中的FactoryBean實(shí)現(xiàn)原理詳解,spring中有兩種類型的Bean,一種是普通的JavaBean,另一種就是工廠Bean(FactoryBean),這兩種Bean都受Spring的IoC容器管理,但它們之間卻有一些區(qū)別,需要的朋友可以參考下2024-02-02

