溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

SpringMVC KindEditor在線編輯器之文件上傳的示例分析

發(fā)布時(shí)間:2021-07-24 11:58:39 來源:億速云 閱讀:129 作者:小新 欄目:編程語言

這篇文章主要介紹了SpringMVC KindEditor在線編輯器之文件上傳的示例分析,具有一定借鑒價(jià)值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

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("請選擇文件。"));
				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 {
			//根目錄路徑,可以指定絕對路徑
			String rootPath = request.getSession().getServletContext().getRealPath(PATH_LINE) + "kindeditor"+PATH_LINE+"attached"+PATH_LINE;
			//根目錄URL,可以指定絕對路徑,比如 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)到上一級目錄
			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)方法大致相同,最終效果如下:

SpringMVC KindEditor在線編輯器之文件上傳的示例分析

感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“SpringMVC KindEditor在線編輯器之文件上傳的示例分析”這篇文章對大家有幫助,同時(shí)也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識等著你來學(xué)習(xí)!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI