KindEditor 远程上传跨域

kindeditor

  • 引入KindEditor 相关js
<script type="text/javascript" src="static/js/kindeditor-4.1.10/kindeditor-all.js"></script>
<script type="text/javascript" src="static/js/kindeditor-4.1.10/lang/zh_CN.js"></script>
  • 页面加入textarea 标签
<textarea id="details" runat="server" name="details" style="height: 500px;" class="form-control"></textarea>
  • 初始化富文本
	//富文本初始化开始
	var editor,callBackPath ="http://"+window.location.host+'${request.contextPath}/public/KindEditorCallBack';
	KindEditor.ready(function(K) {
		editor = K.create('textarea[name="details"]', {
			uploadJson : "http://远程服务器地址/file-server/upload/kindEditorUpload?callBackPath="+callBackPath,//上传回调
			fileManagerJson : "http://远程服务器地址/file-server/upload/kindeditorFileManagerx",//文件管理
			allowImageUpload: true, //多图上传
			allowFileManager : true, //浏览图片空间
			filterMode : false, //HTML特殊代码过滤
			afterBlur: function(){ this.sync(); },//编辑器失去焦点(blur)时执行的回调
		});
		
	});
	//富文本初始化结束
  • callBackPath 是回调的controller地址(是你使用富文本的当前项目回调页面地址)

  • 回调页面服务端controller

	/**
	* @Title: KindEditorCallBack
	* @Description: TODO(富文本iframe跨域回调)
	* @param 
	* @author gangyu2
	 * @throws UnsupportedEncodingException 
	* @date 2019年1月5日下午12:38:54
	 */
	@GetMapping("KindEditorCallBack")
	public String KindEditorCallBack() throws UnsupportedEncodingException{
		   return "callback/KindEditorCallBack";
	}

回调页面html(放到你需要使用富文本的项目中)

<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
   <script type="text/javascript">
   function getParameter(val) {
       var uri = decodeURI(window.location.search);
       var re = new RegExp("" + val + "=([^&?]*)", "ig");
       return ((uri.match(re)) ? (uri.match(re)[0].substr(val.length + 1)) : null);
   }

       var upload_callback = function() {
           var error = getParameter("error");
           error = parseInt(error)
           var dataObject;
           if(error==0){
               var url = getParameter("url");
               dataObject = {"error": error, "url": url};
           }else{
               var message = getParameter("message");
               dataObject = {"error": error, "message": message};
           }
           var data =  JSON.stringify(dataObject)
           console.log(data);
           document.getElementsByTagName("body")[0].innerHTML = '<pre>' + data + '</pre>';
       }
   </script>
</head>
<body "upload_callback();">
</body>
</html>
  • UploadUtils.java 工具类
package com.jx.file.utils;

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
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 java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

public class UploadUtils {
//
//	/**批量上传总大小50**/
//	public static long TOTAL_SIZE=52428800L;
//	/**单个最大十兆10M**/
//	public static long TEN_M = 10485760L;
	
	/**
	* @Title: fileUp 
	* @Description: TODO(文件上传) 
	* @param filePath 文件存放位置
	* @param fileUrl 文件服务器地址
	* @param withd 大于0压缩
	* @param height 大于0压缩
	* @param request
	* @param response
	* @return Result
	* @param @throws ServletException
	* @param @throws IOException    设定文件 
	* @return Map<String,Object>    返回类型 
	* @auth gyu 
	* @date 2016年11月3日 下午5:01:31
	 */
	public static Result fileUp(String filePath,String fileUrl,int width,int height,HttpServletRequest request) throws ServletException, IOException {
		CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(request.getSession().getServletContext());
		List<Map<String,Object>> fileList=new ArrayList<Map<String,Object>>();
		String ymd = DateUtil.fileTime();
		if(multipartResolver.isMultipart(request))
	     {
	    		String savePath = filePath;
	    		// 定义允许上传的文件扩展名
	    		HashMap<String, String> extMap = new HashMap<String, String>();
	    		extMap.put("img", "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", "apk,doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");
	    		if (!ServletFileUpload.isMultipartContent(request)) {
	    			return new Result(CodeEnum.NOT_FILE);
	    		}
	    		String fileType=request.getParameter("fileType"),dir=request.getParameter("dir"),dirName="";
	    		if(StringUtils.isNoneBlank(fileType)){
	    			dirName=fileType;
	    		}else if(StringUtils.isNotBlank(dir)){//兼容富文本 目录
	    			dirName=dir;
	    		}else{
		    		//默认img
	    			dirName = "img";
	    		}
	    		if (!extMap.containsKey(dirName)) {
	    			return new Result(CodeEnum.DIR_FAIL,new String[]{"img","flash","media","file"});
	    		}
	    		// 创建文件夹
	    		savePath +="/"+dirName+"/"+ymd + "/";
	    		File dirFile = new File(savePath);
	    		if (!dirFile.exists()) {
	    			dirFile.mkdirs();
	    		}

	    		FileItemFactory factory = new DiskFileItemFactory();
	    		ServletFileUpload upload = new ServletFileUpload(factory);
	    		upload.setHeaderEncoding("UTF-8");
				MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
				List<?> ssList=multiRequest.getFiles("file");
//				int size=multiRequest.getContentLength();
//				//检查批量上传大小
//				if(size>TOTAL_SIZE && (ssList!=null && ssList.size()>1)){
//					return new Result(CodeEnum.FILE_TOO_MAX_SIZE);
//				}
				for(Object file:ssList){
					Map<String, Object> fileMap=new HashMap<String,Object>();
					MultipartFile files=(MultipartFile)file;
					String fileName = files.getOriginalFilename();
//					// 检查文件大小
//					if (files.getSize() > TEN_M) {
//		    			return new Result(CodeEnum.FILE_TOO_LARGE);
//					}
					// 检查扩展名
					String fileExt = fileName.substring(
							fileName.lastIndexOf(".") + 1).toLowerCase();
					if (!Arrays.<String> asList(extMap.get(dirName).split(","))
							.contains(fileExt)) {
		    			return new Result(CodeEnum.FORMAT_NOT_SUPPORTED,extMap);
					}

					String newFileName = UUID.randomUUID()+ "." + fileExt;
					try {
						File uploadedFile = new File(savePath, newFileName);
						files.transferTo(uploadedFile);
					} catch (Exception e) {
		    			return new Result(CodeEnum.FAIL);
					}
					//文件http地址
			        String path=fileUrl+"/"+dirName+"/"+ymd+"/"+newFileName;
					//图片缩放http地址
			        String restimgPath=fileUrl+"/"+dirName+"/"+ymd+"/T"+newFileName;
			        //缩放标志
			        boolean zoomFlag=false;
			        if(dirName.equals("img")){
			        	//缩放文件和源文件名字一样 缩放文件 第一个字符T标识 例如:T7d73fc3d-c608-48f1-b839-e2fb27f25c03.jpg
				        zoomFlag=ImageUtils.resize(savePath+"/"+newFileName, savePath+"/T"+newFileName, width, height);
			        }
					if (dirName.equals("flash")) {
						fileMap.put("flash", path);
					} else if (dirName.equals("media")) {
						fileMap.put("media",path);
					} else if (dirName.equals("file")) {
						fileMap.put("file", path);
					} else {
						fileMap.put("img", path);
					}
					if(zoomFlag){
						fileMap.put("restImg", restimgPath);
					}
					fileList.add(fileMap);
				}
	     }
		if(!fileList.isEmpty()){
    		return new Result(CodeEnum.SUCCESS,fileList);
		}else{
    		return new Result(CodeEnum.FAIL,fileList);
		}
	}
	
	
	public static Map<String,Object> imgOriginal(String filePath,String fileUrl,HttpServletRequest request, HttpServletResponse response){

		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");

		int width = 0, height = 0;

		String ymd = DateUtil.fileTime();
		
		String imgPath = "", fileName = "", message = "", state = "success", realFileName = "";
		try {
			// 判断路径是否存在,不存在则创建
    		filePath=filePath+"/img/"+ymd;
			File dir = new File(filePath);
			if (!dir.exists()){
				dir.mkdirs();
			}
			if (ServletFileUpload.isMultipartContent(request)) {

				MultipartHttpServletRequest multRequest = (MultipartHttpServletRequest) request;

				Iterator<?> iter = multRequest.getFileNames();
				while (iter.hasNext()) {
					// 一次遍历所有文件
					MultipartFile file = multRequest.getFile(iter.next().toString());
					if (file != null) {
						try {
							if (file.getName().length() > 0) {
								fileName = file.getOriginalFilename();
								Pattern reg = Pattern.compile("[.]jpg|png|jpeg|gif$");
								Matcher matcher = reg.matcher(fileName);
								if (!matcher.find()) {
									message = "文件类型不允许!";
									state = "error";
									break;
								}
								String FileName = UUID.randomUUID() + "";

								realFileName = FileName + fileName.substring(fileName.lastIndexOf("."), fileName.length());

								imgPath = filePath + "/" + realFileName;

								BufferedInputStream in = new BufferedInputStream(file.getInputStream());// 获得文件输入流
								FileOutputStream a = new FileOutputStream(new File(imgPath));
								BufferedOutputStream output = new BufferedOutputStream(a);
								Streams.copy(in, output, true);// 开始把文件写到你指定的上传文件夹
								BufferedImage buff = ImageIO.read(new File(imgPath));
								width = buff.getWidth();// 获取宽
								height = buff.getHeight();// 获取高

							}

						} catch (Exception e) {
							e.printStackTrace();
						}
					} else {
						state = "error";
						message = "请选择文件";
					}
				}

				String url = fileUrl+"/img/" + ymd + "/" + realFileName;
				return result(state, message, url, width, height);
			}
		} catch (Exception ee) {
			ee.printStackTrace();
		}
		return result(state, message, fileUrl, width, height);
	}
	
	public static Map<String,Object> imgCrop(String filePath,String fileUrl,HttpServletRequest request, HttpServletResponse response) throws IOException{

		String ymd = DateUtil.fileTime();
		String imgUrl = request.getParameter("imgUrl");
		// resized sizes
		String imgW = request.getParameter("imgW");
		String imgH = request.getParameter("imgH");
		// offsets
		String imgY1 = request.getParameter("imgY1");
		String imgX1 = request.getParameter("imgX1");
		// crop box
		String cropW = request.getParameter("cropW");
		String cropH = request.getParameter("cropH");
		// rotation angle
		String rotation = request.getParameter("rotation");

		String realimgUrl = imgUrl.substring(imgUrl.lastIndexOf("/"), imgUrl.length());
		String FileName = "T" + realimgUrl.substring(realimgUrl.lastIndexOf("/") + 1, realimgUrl.lastIndexOf("."));
		String restDir=filePath+"/img/"+ymd;
		String lastFileName = restDir + "/" + FileName + imgUrl.substring(imgUrl.lastIndexOf("."), imgUrl.length());
		String suffix = imgUrl.substring(imgUrl.lastIndexOf("."), imgUrl.length());
		File file = new File(restDir + "/" + realimgUrl);
		File outFile = new File(lastFileName);

		BufferedImage bufferedImage2 = ImageUtils.shearImage(ImageIO.read(file), Integer.parseInt(imgW),
				Integer.parseInt(imgH), Integer.parseInt(imgX1), Integer.parseInt(imgY1), Integer.parseInt(cropW),
				Integer.parseInt(cropH), Integer.parseInt(rotation));
		ImageIO.write(bufferedImage2, "jpg", outFile);
		Map<String, Object> resultJsonObject = new HashMap<String, Object>();
		resultJsonObject.put("status", "success");
		resultJsonObject.put("img", FileName + suffix);
		
		//返回地址
		String url = fileUrl+"/img/" + ymd + "/" + FileName + suffix;
		resultJsonObject.put("url", url);
		return resultJsonObject;
	}
	public static Map<String, Object> result(String state, String message, String url, int width, int height) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("status", state);
		map.put("message", message);
		map.put("url", url);
		map.put("width", width);
		map.put("height", height);
		return map;
	}
	
	/**
	* @Title: kindeditorFileManager
	* @Description: TODO(富文本图片空间)
	* @author gangyu2
	* @date 2019年1月5日下午12:46:58
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static Map<String,Object> fileManager(String filePath,String fileUrl,HttpServletRequest request) throws IOException{
		//根目录路径,可以指定绝对路径,比如 /var/www/attached/
		String rootPath = filePath;
		//根目录URL,可以指定绝对路径,比如 http://www.yoursite.com/attached/
		String rootUrl  = fileUrl;
		//图片扩展名
		String[] fileTypes = new String[]{"gif", "jpg", "jpeg", "png", "bmp"};

		String dirName = request.getParameter("dir");
		if (dirName != null) {
			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";

		File currentPathFile = new File(currentPath);

		//遍历目录取的文件信息
		List<Hashtable> fileList = new ArrayList<Hashtable>();
		if(currentPathFile.listFiles() != null) {
			for (File file : currentPathFile.listFiles()) {
				Hashtable hash = new Hashtable();
				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());
		}
		Map<String,Object> result = new HashMap<String,Object>();
		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);

		return result;
		
	}

	@SuppressWarnings("rawtypes")
	public static 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"));
			}
		}
	}
	
	@SuppressWarnings("rawtypes")
	public static 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;
				}
			}
		}
	}
	
	@SuppressWarnings("rawtypes")
	public static 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"));
			}
		}
	}
	
}

  • ImageUtils.java 图片处理工具类
package com.jx.file.utils;

import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import net.coobird.thumbnailator.Thumbnails;

/**
 * 图片工具类
 */
public final class ImageUtils {

	/**
	 * 图片缩放
	 * 
	 * @param org
	 *            原图路径
	 * @param dest
	 *            缩放图路径
	 * @param imgName
	 *            文件名
	 * @param height
	 *            高度	
	 * @param width
	 *            宽度
	 */
	public static boolean resize(String org, String dest, int height, int width) {
		boolean bol = false; // 是否进行了压缩
		if (height == 0 || width == 0) {
			return false;
		}
		File orgFile=new File(org);
		File destFile=new File(dest);
		try {
			//keepAspectRatio=true 保持比例不变
			Thumbnails.of(orgFile).size(width, height).keepAspectRatio(true).toFile(destFile);
			bol = true;
		} catch (IOException e1) {
			e1.printStackTrace();
		}

		return bol;
	}

	public static void copyFile(String sourcePath, String targetPath) {
		BufferedInputStream inBuff = null;
		BufferedOutputStream outBuff = null;
		try {
			File sourceFile = new File(sourcePath);
			File targetFile = new File(targetPath);
			if (!targetFile.exists()) {
				targetFile.getParentFile().mkdirs();
			}
			inBuff = new BufferedInputStream(new FileInputStream(sourceFile));

			outBuff = new BufferedOutputStream(new FileOutputStream(targetFile));

			byte[] b = new byte[1024 * 5];
			int len;
			while ((len = inBuff.read(b)) != -1) {
				outBuff.write(b, 0, len);
			}
			outBuff.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (inBuff != null)
					inBuff.close();
				if (outBuff != null)
					outBuff.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}

	public static BufferedImage shearImage(BufferedImage srcImage, Integer imgW, Integer imgH, Integer x, Integer y,
			Integer width, Integer height, Integer angel) {
		if (imgW == null) {
			imgW = srcImage.getWidth();
		}
		if (imgH == null) {
			imgH = srcImage.getHeight();
		}
		Image image = scaledImage(srcImage, imgW, imgH);
		BufferedImage bufferedImage = rotateImage(image, angel);
		Image image2 = cropImage(bufferedImage, x, y, width, height);
		BufferedImage shearBufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics2D graphics2d = (Graphics2D) shearBufferedImage.getGraphics();
		graphics2d.drawImage(image2, 0, 0, null);
		graphics2d.dispose();
		return shearBufferedImage;
	}

	public static Image scaledImage(BufferedImage srcImage, Integer imgW, Integer imgH) {
		return srcImage.getScaledInstance(imgW, imgH, Image.SCALE_SMOOTH);
	}

	public static Image cropImage(BufferedImage bufferedImage, Integer x, Integer y, Integer width, Integer height) {
		CropImageFilter cropImageFilter = new CropImageFilter(x, y, width, height);
		FilteredImageSource filteredImageSource = new FilteredImageSource(bufferedImage.getSource(), cropImageFilter);
		return Toolkit.getDefaultToolkit().createImage(filteredImageSource);
	}

	public static BufferedImage rotateImage(Image src, int angel) {
		int src_width = src.getWidth(null);
		int src_height = src.getHeight(null);
		Rectangle rect_des = calcRotatedSize(new Rectangle(new Dimension(src_width, src_height)), angel);
		BufferedImage bufferedImage = new BufferedImage(rect_des.width, rect_des.height, BufferedImage.TYPE_INT_RGB);
		Graphics2D g2 = bufferedImage.createGraphics();
		g2.translate((rect_des.width - src_width) / 2, (rect_des.height - src_height) / 2);
		g2.rotate(Math.toRadians(angel), src_width / 2, src_height / 2);
		g2.drawImage(src, null, null);
		g2.dispose();
		return bufferedImage;
	}

	private static Rectangle calcRotatedSize(Rectangle src, int angel) {
		if (angel >= 90) {
			if (angel / 90 % 2 == 1) {
				int temp = src.height;
				src.height = src.width;
				src.width = temp;
			}
			angel = angel % 90;
		}
		double r = Math.sqrt(src.height * src.height + src.width * src.width) / 2;
		double len = 2 * Math.sin(Math.toRadians(angel) / 2) * r;
		double angel_alpha = (Math.PI - Math.toRadians(angel)) / 2;
		double angel_dalta_width = Math.atan((double) src.height / src.width);
		double angel_dalta_height = Math.atan((double) src.width / src.height);

		int len_dalta_width = (int) (len * Math.cos(Math.PI - angel_alpha - angel_dalta_width));
		int len_dalta_height = (int) (len * Math.cos(Math.PI - angel_alpha - angel_dalta_height));
		int des_width = src.width + len_dalta_width * 2;
		int des_height = src.height + len_dalta_height * 2;
		return new Rectangle(new Dimension(des_width, des_height));
	}

}
  • 上传大小这里禁用了写在配置文件里(springboot配置方式)
#是单个文件大小
spring.servlet.multipart.max-file-size=10MB
#maxRequestSize是设置总上传的数据大小
spring.servlet.multipart.max-request-size=50MB
  • 远程上传服务controller
/**    
* @Title: UploadController.java  
* @Package com.jx.admin.web.controller.base  
* @Description: TODO(上传接口)  
* @author gangyu
* @date 2018年12月27日 上午10:26:11  
* @version V1.0    
*/
package com.jx.file.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileUploadException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
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 org.springframework.web.servlet.ModelAndView;

import com.jx.file.utils.Result;
import com.jx.file.utils.UploadUtils;

/**
 * @ClassName: UploadController
 * @Description: TODO(文件上传)
 * @author gangyu
 * @date 2018年12月27日 上午10:26:11
 * 
 */
@RequestMapping("/upload")
@Controller
public class UploadController {

	@Value("${file.path:'D:/file/upload'}")
	public String FILE_PATH;

	@Value("${file.url:'http://192.168.1.189/file/upload'}")
	public String FILE_URL;

	/**
	 * @Title: upload
	 * @Description: TODO(图片上传原图)
	 * @author gangyu2
	 * @date 2018年12月27日下午3:46:57
	 */
	@RequestMapping(value = "/imgOriginal", method = RequestMethod.POST)
	@ResponseBody
	public Object upload(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		return UploadUtils.imgOriginal(FILE_PATH, FILE_URL, request, response);
	}

	/**
	 * @Title: doPost
	 * @Description: TODO(图片上传裁剪)
	 * @author gangyu2
	 * @date 2018年12月27日下午3:47:34
	 */
	@RequestMapping(value = "/imgCrop", method = RequestMethod.POST)
	@ResponseBody
	protected Object doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		return UploadUtils.imgCrop(FILE_PATH, FILE_URL, request, response);
	}

	/**
	 * @Title: file_upload
	 * @Description: TODO(通用图片上传)
	 * @param width 默认 0
	 * @param height  默认 0
	 * @author gangyu2
	 * @date 2018年12月27日下午3:48:13
	 */
	@ResponseBody
	@RequestMapping(value = "/fileUpload")
	public Object file_upload(@RequestParam(value = "width", defaultValue = "0") Integer width,
			@RequestParam(value = "height", defaultValue = "0") Integer height, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		return UploadUtils.fileUp(FILE_PATH, FILE_URL, width, height, request);
	}
	
	/**
	* @Title: uploadKindEditor
	* @Description: TODO(富文本上传)
	* @author gangyu2
	* @date 2019年1月5日下午1:53:02
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/kindEditorUpload", produces = "application/json; charset=utf-8", method = RequestMethod.POST)
    public ModelAndView uploadKindEditor(@RequestParam String callBackPath,@RequestBody MultipartFile imgFile,HttpServletRequest request) throws IOException{
		Map<String, Object> params = new HashMap<String, Object>();
		String url="";
		try {
			Result result=UploadUtils.fileUp(FILE_PATH, FILE_URL, 0, 0, request);
            if(result.getCode().equals("0")){
            	List<Map<String,Object>> fileList=(List<Map<String, Object>>) result.getData();
            	if(fileList.isEmpty()){
        			url = "redirect:" + callBackPath + "?error=1&message="+java.net.URLEncoder.encode("上传出错","UTF-8");
            	}else{
                	Map<String,Object> map=fileList.get(0);
                	String dir=request.getParameter("dir");
                    url = "redirect:" + callBackPath + "?error=0&url="+map.get(dir);
            	}
            }else{
    			url = "redirect:" + callBackPath + "?error=1&message="+java.net.URLEncoder.encode(result.getMsg(),"UTF-8");
            }
		} catch (Exception e) {
			params.put("state", "ERROR");
			url = "redirect:" + callBackPath + "?error=1&message="+java.net.URLEncoder.encode("上传出错","UTF-8");
		}
        return new ModelAndView(url);
    }

	/**
	 * 图片空间
	 * @throws IOException
	 * @throws FileUploadException
	 */
	@ResponseBody
	@RequestMapping(value = "kindeditorFileManager.do", method = RequestMethod.GET)
	public Object kindeditorFileManager(HttpServletRequest request, HttpServletResponse response) throws IOException, FileUploadException {
		return UploadUtils.fileManager(FILE_PATH, FILE_URL, request);
	}

}

  • 其中 imgOriginal & imgCrop 是 croppic.js 裁剪工具使用的方法
  • croppic裁剪插件
  • 当然 UploadUtils.fileUp 此方法也支持图片压缩 使用 net.coobird.thumbnailator.Thumbnails 方法
  • 最后通过Nginx 把图片代理出来 就完成了
  • 代理上传静态资源
  • 告辞
展开阅读全文

没有更多推荐了,返回首页