package com.xxxx.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.xxx.hcxg.commons.utils.lang.DateUtils;
import com.xxx.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>
效果: