JSP部分:
$(document).ready(function(){
var editor = KindEditor.create('textarea[name="detail"]', {
uploadJson : '<%=basePath %>templet/editor_upload_gate/shop${shopId}',
width : '100%',
height : '300',
items: [
'undo', 'redo', '|', 'justifyleft', 'justifycenter', 'justifyright',
'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript',
'superscript', '|',
'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold',
'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|',
'image',
'table', 'hr', 'emoticons','|', 'clearhtml', 'selectall', 'fullscreen',
],
allowFlashUpload : false,
allowMediaUpload : false,
allowFileUpload : true,
});
});
KindEditor.ready(function(K) {
var uploadeditor = K.editor({
uploadJson : '<%=basePath %>templet/editor_upload_gate/shop${shopId}',
allowFileManager : true
});
K('#image3').click(function() {
uploadeditor.loadPlugin('image', function() {
uploadeditor.plugin.imageDialog({
showRemote : false,
clickFn : function(url, title, width, height, border, align) {
$("#wjtp ul").empty();
$("#wjtp ul").append("<li><input type=hidden id='advertImage' name='advertImage' value='" + url +"'/><img width=180 height=180 src='" + url +"' /><span class=\"sublh_bq\"><em class=\"fr1\"><a href='#' οnclick=\"delPic()\">删除</a></em></span></li>");
uploadeditor.hideDialog();
}
});
});
});
});
后台部分Java代码:
@SuppressWarnings("unchecked")
@RequestMapping(value = "/editor_upload_gate/{updatepath}", produces="text/plain;charset=UTF-8")
public @ResponseBody String brandeditor_upload_gate(@PathVariable("updatepath") String updatepath, @RequestParam(value="dir", required = false) String dirName, HttpServletRequest request, HttpServletResponse response) {
JSONObject ajaxResult = new JSONObject();
String savePath = request.getSession().getServletContext().getRealPath("/") + "/upload/" + updatepath + "/";
//文件保存目录URL
String saveUrl = request.getContextPath() + "/upload/" + updatepath + "/";
//定义允许上传的文件扩展名
HashMap<String, String> extMap = new HashMap<String, String>();
extMap.put("image", "gif,jpg,jpeg,png");
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,txt,zip,rar,gz,bz2");
//最大文件大小
long maxSize = 450000;
if(!ServletFileUpload.isMultipartContent(request)){
ajaxResult.put("error", "1");
ajaxResult.put("message", "请选择文件。");
return ajaxResult.toJSONString();
}
//检查目录
File uploadDir = new File(savePath);
if (!uploadDir.exists()) {
uploadDir.mkdirs();
}
if(!uploadDir.isDirectory()){
ajaxResult.put("error", "1");
ajaxResult.put("message", "上传目录不存在。");
return ajaxResult.toJSONString();
}
//检查目录写权限
if(!uploadDir.canWrite()){
ajaxResult.put("error", "1");
ajaxResult.put("message", "上传目录没有写权限。");
return ajaxResult.toJSONString();
}
if(dirName == null) {
dirName = "image";
}
if(!extMap.containsKey(dirName)){
ajaxResult.put("error", "1");
ajaxResult.put("message", "目录名不正确。");
return ajaxResult.toJSONString();
}
//创建文件夹
File dirFile = new File(savePath);
if (!dirFile.exists()) {
dirFile.mkdirs();
}
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
DefaultMultipartHttpServletRequest mrequest= (DefaultMultipartHttpServletRequest)request;
Map map = mrequest.getFileMap();
Collection<MultipartFile> c = map.values();
Iterator it = c.iterator();
for(; it.hasNext();) {
CommonsMultipartFile file=(CommonsMultipartFile) it.next();
if(!file.isEmpty()) {
long fileSize = file.getSize();
String fileName = file.getOriginalFilename();
String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
if(fileSize > maxSize){
ajaxResult.put("error", "1");
ajaxResult.put("message", "上传文件大小超过限制, 最大允许450KB。");
return ajaxResult.toJSONString();
}
if(!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)){
ajaxResult.put("error", "1");
ajaxResult.put("message", "上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。");
return ajaxResult.toJSONString();
}
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
String newFileName_s = df.format(new Date()) + "_" + new Random().nextInt(1000) + "_s" + "." + fileExt;
File uploadedFile = new File(savePath, newFileName);
File uploadedFile_s = new File(savePath, newFileName_s);
try {
file.transferTo(uploadedFile);
} catch(Exception e) {
ajaxResult.put("error", "1");
ajaxResult.put("message", "上传文件失败。");
e.printStackTrace();
return ajaxResult.toJSONString();
}
// 压缩图片、删除压缩前的图片
compressPic(uploadedFile, uploadedFile_s, 800);
uploadedFile.delete();
ajaxResult.put("error", 0);
ajaxResult.put("url", saveUrl + newFileName_s);
ajaxResult.put("title", fileName);
return ajaxResult.toJSONString();
} else {
ajaxResult.put("error", "1");
ajaxResult.put("url", "不可以上传空文件!");
return ajaxResult.toJSONString();
}
}
return ajaxResult.toJSONString();
}
// 图片压缩处理
@SuppressWarnings("restriction")
public void compressPic(File inputFile, File outputFile, int rate) {
try {
Image img = ImageIO.read(inputFile);
// 判断图片格式是否正确
if (img.getWidth(null) != -1) {
int newWidth;
int newHeight;
// 等比缩放
// 为等比缩放计算输出的图片宽度及高度
double rate1 = ((double) img.getWidth(null)) / (double) rate + 0.1;
// 根据缩放比率大的进行缩放控制
newWidth = (int) (((double) img.getWidth(null)) / rate1);
newHeight = (int) (((double) img.getHeight(null)) / rate1);
BufferedImage tag = new BufferedImage((int) newWidth, (int) newHeight, BufferedImage.TYPE_INT_RGB);
// Image.SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的 优先级比速度高 生成的图片质量比较好 但速度慢
tag.getGraphics().drawImage(
img.getScaledInstance(newWidth, newHeight,
Image.SCALE_SMOOTH), 0, 0, null);
FileOutputStream out = new FileOutputStream(outputFile);
// JPEGImageEncoder可适用于其他图片类型的转换
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag);
out.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}