kindeditor-4.1.10 ---文件上传

package com.zsplat.hcxg.commons.utils.web.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;

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

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.zsplat.hcxg.commons.utils.lang.DateUtils;
import com.zsplat.hcxg.commons.utils.lang.PropertiesUtil;

/**
 *
 * @ClassName:FileUploadServlet
 * @Description:TODO(kindeditor-4.1.10富文本编辑器上传组件)
 *
 * @Copyright: 2017 www.zsplat.com Inc. All rights reserved.
 */
public class FileUploadServlet extends HttpServlet {
	//上传路径<Linux>
	private final String ROOT = File.separator + "home"+ File.separator +"image"+ File.separator;
//	private final String ROOT = "D:" + File.separator + "resourcesfile"+ File.separator +"images"+ File.separator;

	private static final long serialVersionUID = 1L;
	// 定义允许上传的文件扩展名
	protected HashMap<String, String> extMap = new HashMap<String, String>();
	// 最大文件大小
	protected long maxSize = 100000000;
	// 上传文件的保存路径
	protected String configPath = "kindeditor" + File.separator;

	public void init() throws ServletException {
		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,pdf,ppt,htm,html,txt,zip,rar,gz,bz2");
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String dirName = request.getParameter("dir");
		if (dirName == null) {
			dirName = "image";
		}
		if ("image".equals(dirName)) {
			// 上传的图片大小
			Long size = Long.parseLong(getInitParameter("Img_MAX_SIZE"));
			if (size != null) {
				maxSize = size;
			}
			// 上传图片的类型(缺省值为gif, jpg, jpeg, png, bmp)
			String type = getInitParameter("Img_YPES");
			if (type != null) {
				extMap.put("image", type);
			}
		} else {
			// 上传的图片大小
			Long size = Long.parseLong(getInitParameter("File_MAX_SIZE"));
			if (size != null) {
				maxSize = size;
			}

			if ("file".equals(dirName)) {
				// 上传文件的类型(doc, xls, ppt, pdf, txt, rar, zip)
				String type = getInitParameter("File_TYPES");
				if (type != null) {
					extMap.put("file", type);
				}
			}
		}
		if (configPath == null) {
			renderText(getError("你还没设置上传文件保存的目录路径!"), response);
			return;
		}
		// 文件保存目录路径
		String savePath = ROOT + configPath;
		if (!ServletFileUpload.isMultipartContent(request)) {
			renderText(getError("请选择文件。"), response);
			return;
		}
		// 检查目录
		File uploadDir = new File(savePath);
		if(!uploadDir.exists()){
			uploadDir.mkdirs();
		}
		// 检查目录写权限
		if (!uploadDir.canWrite()) {
			renderText(getError("传目录没有写权限。"), response);
			return;
		}

		if (!extMap.containsKey(dirName)) {
			renderText(getError("目录名不正确。"), response);
			return;
		}
		// 创建文件夹
		String date = DateUtils.getCurrentTime("yyyy-MM-dd");
		savePath += date + File.separator;
		File dirFile = new File(savePath);
		if (!dirFile.exists()) {
			dirFile.mkdirs();
		}

		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setHeaderEncoding("UTF-8");

		try {
			List<?> items = upload.parseRequest(request);
			Iterator<?> itr = items.iterator();
			while (itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				String fileName = item.getName();
				//long fileSize = item.getSize();
				if (!item.isFormField()) {
					// 检查文件大小
					if (item.getSize() > maxSize) {
						renderText(getError("上传文件大小超过限制。"), response);
						return;
					}
					// 检查扩展名
					String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
					if (!Arrays.<String> asList(extMap.get(dirName).split(",")).contains(fileExt)) {
						renderText(getError("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。"), response);
						return;
					}
					String newFileName = DateUtils.getCurrentTime("yyyyMMddHHmmss") + new Random().nextInt(1000) + "." + fileExt;
					try {
						File uploadedFile = new File(savePath, newFileName);
						item.write(uploadedFile);
					} catch (Exception e) {
						renderText(getError("上传文件失败。"), response);
						return;
					}

					Map<String, Object> obj = new HashMap<String, Object>();
					obj.put("error", 0);
					String returnImgUrl = PropertiesUtil.loadResource("IMG_HTTP_SERVER", "image.properties") + configPath + date + File.separator + newFileName;
					returnImgUrl = returnImgUrl.replaceAll("\\\\", "/");
					obj.put("url", returnImgUrl);
					renderText(obj, response);
				}
			}
		} catch (FileUploadException e1) {
			e1.printStackTrace();
		}
	}

	private Map<String, Object> getError(String message) {
		Map<String, Object> obj = new HashMap<String, Object>();
		obj.put("error", 1);
		obj.put("message", message);
		return obj;
	}

	/**
	 *
	 * @Title: renderText
	 * @Description: TODO(输出 html/text格式 json字符串 <br>自动将data参数转换为json字符串)
	 * @param data
	 * 				         输出数据 可以是List Map等
	 * @return void    返回类型
	 * @throws
	 */
	public void renderText(Object data, HttpServletResponse response) {
		response.setContentType("text/plain;charset=UTF-8");
		setDisableCacheHeader(response);
		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.print(JsonMapper.nonEmptyMapper().toJson(data));
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}

	/**
	 *
	 * @Title: setDisableCacheHeader
	 * @Description: TODO(设置禁止客户端缓存的Header.)
	 * @param @param response    设定文件
	 * @return void    返回类型
	 * @throws
	 */
	public void setDisableCacheHeader(HttpServletResponse response) {
		// Http 1.0 header
		response.setDateHeader("Expires", 1L);
		response.addHeader("Pragma", "no-cache");
		// Http 1.1 header
		response.setHeader("Cache-Control", "no-cache, no-store, max-age=0");
	}

}

  js中    富文本编辑器中调用文件上传的接口

       var serviceDetails;
            window.setTimeout(function() {
                serviceDetails = KindEditor.create(‘#serviceDetails‘, {
                    //width : ‘700px‘,
                    height : ‘250px‘,
                    minWidth:‘650px‘,//默认最小值为"650px"
                    items : [ ‘source‘, ‘|‘, ‘undo‘, ‘redo‘, ‘|‘, ‘preview‘, ‘print‘, ‘template‘, ‘code‘, ‘cut‘, ‘copy‘, ‘paste‘, ‘plainpaste‘, ‘wordpaste‘, ‘|‘, ‘justifyleft‘, ‘justifycenter‘, ‘justifyright‘, ‘justifyfull‘, ‘insertorderedlist‘, ‘insertunorderedlist‘, ‘indent‘, ‘outdent‘, ‘subscript‘, ‘superscript‘, ‘clearhtml‘, ‘quickformat‘, ‘selectall‘, ‘|‘, ‘fullscreen‘, ‘/‘, ‘formatblock‘, ‘fontname‘, ‘fontsize‘, ‘|‘, ‘forecolor‘, ‘hilitecolor‘, ‘bold‘, ‘italic‘, ‘underline‘, ‘strikethrough‘, ‘lineheight‘, ‘removeformat‘, ‘|‘, ‘image‘, ‘flash‘, ‘media‘, ‘insertfile‘, ‘table‘, ‘hr‘, ‘emoticons‘, ‘baidumap‘, ‘pagebreak‘, ‘anchor‘, ‘link‘, ‘unlink‘ ],
                    allowFileManager : true,
                    uploadJson : ‘servlet/FileUploadServlet‘,
                    fileManagerJson : ‘‘,//servlet/FileManagerServlet
                    afterCreate:function(){ //加载完成后改变皮肤
                        this.sync();
                        var color = $(‘.panel-header‘).css(‘background-color‘);
                        $(‘.ke-toolbar‘).css(‘background-color‘,color);
                    },
                    afterUpload : function(url, data, name){

                    },
                    afterBlur:function(){
                        this.sync();
                    }
                });
            }, 1);

页面中

<link rel="stylesheet" href="library/kindeditor-4.1.10/themes/default/default.css" type="text/css"></link>
<link rel="stylesheet" href="views/appManage/goods/goods/css/addGoods.css" type="text/css"></link>
<script type="text/javascript" src="library/kindeditor-4.1.10/kindeditor-min.js"></script>
<script type="text/javascript" src="library/kindeditor-4.1.10/lang/zh_CN.js"></script>

<form>
 <div class="form-group">
<label for="goodsTitle">商品服务介绍</label>
            <!-- <textarea rows="2" class="form-control" maxlength="300" ng-model="goods.serviceDetails" name="serviceDetails" id="serviceDetails" placeholder="服务详情"></textarea> -->
            <textarea rows="2" class="form-control" ng-model="goods.serviceDetails" name="serviceDetails" id="serviceDetails" placeholder="商品描述"></textarea>
            <label for="goodsTitle">服务过程</label>
            <!-- <textarea rows="2" class="form-control" maxlength="300" ng-model="goods.serviceProcedure" name="serviceProcedure" id="serviceProcedure" placeholder="服务过程"></textarea> -->
            <textarea rows="2" class="form-control" ng-model="goods.serviceProcedure" name="serviceProcedure" id="serviceProcedure" placeholder="商品描述"></textarea>
        </div>
</form>

效果:

原文地址:https://www.cnblogs.com/zhou-pan/p/9239240.html

时间: 2024-08-30 16:34:26

kindeditor-4.1.10 ---文件上传的相关文章

Javaweb学习笔记10—文件上传与下载

 今天来讲javaweb的第10阶段学习.文件的上传与下载,今天主要说的是这个功能的实现,不用说了,听名字就是外行人也知道肯定很重要啦. 老规矩,首先先用一张思维导图来展现今天的博客内容. ps:我的思维是用的xMind画的,如果你对我的思维导图感兴趣并且想看到你们跟详细的备注信息,请点击下载 另外:如果图看不清的话请右击---在新窗口中打开会清楚很多 一*, 文件的上传:      1 *分析实现步骤: 1.1* 客户端浏览器通过文件域选择本地要上传的文件. * 点击"上传"按钮

Struts2笔记——10.文件上传

只有当表单的method为post,并且enctype要设置为multipart/form-data时,本地的二进制文件才能够上传到服务器.Struts2本身并不会去解析multipart/form-data,而是需要借助其他框架,所以它的上传功能需要依赖Common-FileUpload.COS等组件.相应的,我们需要把commons-io包跟commons-fileupload包添加到项目中.Struts2对原有的上传解析器做了进一步的封装,使用起来更加简便. 实现文件上传的action S

文件上传插件WebUploader的使用

插件描述: WebUploader是由Baidu WebFE(FEX)团队开发的一个简单的以HTML5为主,FLASH为辅的现代文件上传组件.在现代的浏览器里面能充分发挥HTML5的优势,同时又不摒弃主流IE浏览器,沿用原来的FLASH运行时,兼容IE6+,iOS 6+, android 4+.两套运行时,同样的调用方式,可供用户任意选用. 采用大文件分片并发上传,极大的提高了文件上传效率. 插件特点: 分片.并发分片与并发结合,将一个大文件分割成多块,并发上传,极大地提高大文件的上传速度.当网

html多文件上传,可支持预览

1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>表单提交</title> 6 <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script> 7 &

我爱Java系列---【SpringMVC传统方式的文件上传和前端获取数据库图片在页面显示】

一.文件上传 说明:传统方式的文件上传,指的是我们上传的文件和访问的应用存在于同一台服务器上.并且上传完成之后,浏览器可能跳转. 1. 第一步:创建 maven 工程并导入 commons-fileupload 坐标 1 <dependency> 2 <groupId>commons-fileupload</groupId> 3 <artifactId>commons-fileupload</artifactId> 4 <version&g

kindeditor 文件上传在 spring mvc下的使用

最近做项目,需要用到文本编辑器,找了一下,决定使用 kindeditor,百度了一下kindeditor 文件上传的 controller的代码,copy下来发现了问题. 测试出来问题是:upload.parseRequest(request) 这一句取的值为空 ,再去百度一下,发现很多人都有这样的问题.主要原因就在于项目其他地方用到了spring mvc 配置好了的上传,配置文件里已经写了.所以 解决方案一是:删除 <bean id="multipartResolver" cl

Python+Selenium学习笔记10 - send_keys上传文件

在火狐浏览器上传文件 上传前,同一个HTML文件在火狐和Edge浏览器显示有些不同 这是Firefox浏览器的显示 这是Edge浏览器 上传后 1 # coding = utf-8 2 3 from selenium import webdriver 4 import os 5 import time 6 7 dr = webdriver.Firefox() 8 file_path = "file:///" + os.path.abspath('upfile.html') 9 dr.g

10.基于Tomcat的SmartUplaod文件上传

文件的上传是项目中常见的核心功能,比如在注册的时候可能在表单中要求用户提交照片等.此时就需要使用到文件的上传,本次课题以上传雇员的照片作为需求,但是在很多时候上传的的需求不仅仅是雇员,可能需要上传管理员头像等等,此时需要增加管理员的信息也可能要上传到servlet.文件上传的第三方工具有很多,我们这次使用的是SmartUpload组件. 1.定义表单(login.jsp) <%@ page language="java" contentType="text/html;

springBoot(10):web开发-文件上传

一.简介 Spring Boot默认使用springMVC包装好的解析器进行上传 二.代码实现 2.1.from表单 <form method="POST" enctype="multipart/form-data" action="/file/upload">     文件:<input type="file" name="roncooFile" />     <input