jsp代码

 1 <script type="text/javascript" src="${pageContext.request.contextPath}/kindeditor/lang/zh-CN.js"></script>
2 <script type="text/javascript" src="${pageContext.request.contextPath}/kindeditor/kindeditor-all.js"></script>
3 <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery.js"></script>
4 <script type="text/javascript">
5 var options = {
6 items:['insertfile','image'],
7 uploadJson:"${pageContext.request.contextPath}/UploadServlet"
8 //uploadJson:"${pageContext.request.contextPath}/kindeditor/jsp/upload_json.jsp"
9 // fileManagerJson : "${pageContext.request.contextPath}/kindeditor/jsp/file_manager_json.jsp",
10 // allowFileManager : true,
11 // afterUpload: function(){this.sync();}
12 };
13
14 KindEditor.ready(function(k) {
15 window.editor = k.create("textarea[name='content1']",options);
16 });
17 </script>
18 </head>
19 <body>
20 <!-- 使用kindeditor上传文件 -->
21 <div style="text-align:center">
22 <form name="example" method="post" action="#">
23 <textarea name="content1" style="width:700px;height:200px;visibility:visible;">
24
25
26 </textarea>
27 <br />
28 <input type="submit" name="button" value="提交内容" /> (提交快捷键: Ctrl + Enter)
29 </form>
30
31 </textarea>
32 </div>
33
34 </body>
35 </html>

UploadServlet

 package cn.tele.servlet;

 import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
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 org.json.simple.JSONObject; public class UploadServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset = utf-8");
//文件保存目录路径
String savePath = request.getSession().getServletContext().getRealPath("/") + "WEB-INF/attached/";
PrintWriter out = response.getWriter();
//文件保存目录URL
String saveUrl = request.getContextPath() + "/WEB-INF/attached/"; //定义允许上传的文件扩展名
HashMap<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,txt,zip,rar,gz,bz2"); //最大文件大小
long maxSize = 1000000000; response.setContentType("text/html; charset=UTF-8"); if(!ServletFileUpload.isMultipartContent(request)){
out.println(getError("请选择文件。"));
return;
}
//检查目录
File uploadDir = new File(savePath);
if(!uploadDir.isDirectory()){
out.println(getError("上传目录不存在。"));
return;
}
//检查目录写权限
if(!uploadDir.canWrite()){
out.println(getError("上传目录没有写权限。"));
return;
} //单独使用组件时要传递dirName,参考demo3.jsp
String dirName = request.getParameter("dir");
if (dirName == null) {
// dirName = "image";
}
System.out.println("dirName--------" + dirName);
if(!extMap.containsKey(dirName)){
out.println(getError("目录名不正确。"));
return;
}
//创建文件夹
// savePath += dirName + "/";
// saveUrl += dirName + "/";
File saveDirFile = new File(savePath);
if (!saveDirFile.exists()) {
saveDirFile.mkdirs();
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String ymd = sdf.format(new Date());
// savePath += ymd + "/";
// saveUrl += ymd + "/";
File dirFile = new File(savePath);
if (!dirFile.exists()) {
dirFile.mkdirs();
} FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
List items;
try {
items = upload.parseRequest(request);
Iterator itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
String fileName = item.getName();
String oldFileName = fileName;
long fileSize = item.getSize();
if (!item.isFormField()) {
//检查文件大小
if(item.getSize() > maxSize){
out.println(getError("上传文件大小超过限制。"));
return;
}
//检查扩展名
String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
if(!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)){
out.println(getError("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。"));
return;
} SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String newFileName = df.format(new Date()) + new Random().nextInt(1000) + "." + fileExt;
File uploadedFile = new File(savePath, newFileName);
item.write(uploadedFile); JSONObject obj = new JSONObject();
obj.put("error", 0);
// obj.put("url", saveUrl + newFileName);
obj.put("url",oldFileName);//回显原文件名
out.println(obj.toJSONString());
}
}
}catch (FileUploadException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset = utf-8");
doGet(request, response);
} private String getError(String message) {
JSONObject obj = new JSONObject();
obj.put("error", 1);
obj.put("message", message);
return obj.toJSONString();
} }

默认的uploadJson是一个jsp页面,我把其中的代码拷贝到了UploadServlet中,并进行了一些修改

1.修改文件夹的创建方式,默认的创建方式是/attached/fiile(或者是image等)/今天日期/,只保留/attached/

2.修改了上传文件的回显名称

默认的回显路径是这种,非常难以辨认,想显示原来的上传文件名怎么办?

只需更改返回的json格式的url的值即可

这样重新上传回显的文件名是这样的

你会发现这样多个/kindeditor(我的项目名),如果想要去除,可以到kindeditor.js中搜索insertfile,注释掉formaturl即可

重新上传,回显文件名

ps:如果操作之后没有变化,清理下浏览器缓存即可

3.关于中文乱码

由于文件名已重新命名,避免文件名重复,所以没有中文编码的问题

测试结果:

至此文件上传已完成,接下来是文件下载

文件下载的思路很简单,在jsp页面显示文件列表,然后io下载即可

ListFileServlet此Servlet用于提供下载列表,将列表显示在jsp页面

 package cn.tele.servlet;

 import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* 显示可供下载的文件列表
* @author Administrator
*
*/
public class ListFileServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset = utf-8");
//使用kindeditor上传的文件均被重命名为:yyyyMMddHHssmm+三位随机数的形式,所以文件名不需要编码转换
String dirPath = this.getServletContext().getRealPath("/WEB-INF/attached/");
Map<String,String> map = new HashMap<String, String>();
File dir = new File(dirPath);
if(dir.isDirectory()) {
File[] files = dir.listFiles();
for(File file : files) {
map.put(file.getName(),file.getAbsolutePath());
}
}
request.setAttribute("map",map);
request.getRequestDispatcher("/WEB-INF/jsp/listFile.jsp").forward(request, response);
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
} }

DownLoadServlet,此Servlet用于提供下载功能,注意千万要设置响应头为content-disposition

注意:此程序没有判断文件是否存在

 package cn.tele.servlet;

 import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException; import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.filechooser.FileNameExtensionFilter; /**
* 文件下载
* @author Administrator
*
*/
public class DownloadServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset = utf-8");
String fileName = request.getParameter("fileName");
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File(fileName)));
byte[] buff = new byte[1024];
ServletOutputStream outputStream = response.getOutputStream();
fileName = fileName.replace("\\","_");
//设置响应头
response.setHeader("content-disposition","attachment;filename="+fileName.substring(fileName.lastIndexOf("_")+1));
BufferedOutputStream bos = new BufferedOutputStream(outputStream);
int count = 0;
while((count=bis.read(buff)) != -1) {
bos.write(buff,0,count);
}
bos.flush();
bos.close();
bis.close();
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
} }

测试结果:

上传图片与之想类似,需要注意的是如果使用了默认的upload_json.jsp和file_manager_json.jsp,要根据你的需要修改其中的代码,比如上传的路径尽量放在WEB-INF下,

使用file_manager_json.jsp.浏览图片空间时会生成一个mage文件夹,可以根据需要修改

kindeditor 4 上传下载文件的更多相关文章

  1. rz和sz上传下载文件工具lrzsz

    ######################### rz和sz上传下载文件工具lrzsz ####################################################### ...

  2. linux上很方便的上传下载文件工具rz和sz

    linux上很方便的上传下载文件工具rz和sz(本文适合linux入门的朋友) ##########################################################&l ...

  3. shell通过ftp实现上传/下载文件

    直接代码,shell文件名为testFtptool.sh: #!/bin/bash ########################################################## ...

  4. SFTP远程连接服务器上传下载文件-qt4.8.0-vs2010编译器-项目实例

    本项目仅测试远程连接服务器,支持上传,下载文件,更多功能开发请看API自行开发. 环境:win7系统,Qt4.8.0版本,vs2010编译器 qt4.8.0-vs2010编译器项目实例下载地址:CSD ...

  5. linux下常用FTP命令 上传下载文件【转】

    1. 连接ftp服务器 格式:ftp [hostname| ip-address]a)在linux命令行下输入: ftp 192.168.1.1 b)服务器询问你用户名和密码,分别输入用户名和相应密码 ...

  6. C#实现http协议支持上传下载文件的GET、POST请求

    C#实现http协议支持上传下载文件的GET.POST请求using System; using System.Collections.Generic; using System.Text; usin ...

  7. HttpClient上传下载文件

    HttpClient上传下载文件 java HttpClient Maven依赖 <dependency> <groupId>org.apache.httpcomponents ...

  8. 初级版python登录验证,上传下载文件加MD5文件校验

    服务器端程序 import socket import json import struct import hashlib import os def md5_code(usr, pwd): ret ...

  9. 如何利用京东云的对象存储(OSS)上传下载文件

    作者:刘冀 在公有云厂商里都有对象存储,京东云也不例外,而且也兼容S3的标准因此可以利用相关的工具去上传下载文件,本文主要记录一下利用CloudBerry Explorer for Amazon S3 ...

随机推荐

  1. Java核心技术 卷Ⅰ 基础知识(5)

    第11章 异常.断言.日志和调试 处理错误 异常分类 声明已检查异常 如何抛出异常 创建异常类 捕获异常 捕获多个异常 再次抛出异常与异常链 finally子句 带资源的try语句 分析堆栈跟踪元素 ...

  2. 在 Windows 10 x64 上安装及使用 ab 工具的流程

    本文转自:www.shuijingwanwq.com/2017/04/18/1568/ 1.基于AB测试工具进行高并发情形下的模拟测试,打开:http://httpd.apache.org/docs/ ...

  3. C#游戏开发高速入门 2.1 构建游戏场景

    C#游戏开发高速入门 2.1  构建游戏场景 假设已经计划好了要编写什么样的游戏,在打开Unity以后.要做的第一件事情就是构建游戏场景(Scene).游戏场景就是玩家游戏时,在游戏视图中看到的一切. ...

  4. 2、Python基本数据类型

    1.算数运算: 2.比较运算: 3.赋值运算: 4.逻辑运算: 5.成员运算: 基本数据类型 1.数字 int(整型) 在32位机器上,整数的位数为32位,取值范围为-2**31-2**31-1,即- ...

  5. AE中Shapefile文件添加到SDE数据集

    linder_lee 原文 AE中Shapefile文件添加到SDE数据集(c#) 主要完成用C#,通过AE将本地Shapefile文件导入到SDE的指定数据集下面. 首先说下思路: (1) 通过Op ...

  6. zeros() 函数——MATLAB

    zeros函数——生成零矩阵 ones函数——生成全1阵 [zeros的使用方法] B=zeros(n):生成n×n全零阵. B=zeros(m,n):生成m×n全零阵. B=zeros([m n]) ...

  7. 【t086】防护伞

    Time Limit: 1 second Memory Limit: 128 MB [问题描述] 据说2012的灾难和太阳黑子的爆发有关.于是地球防卫小队决定制造一个特殊防护伞,挡住太阳黑子爆发的区域 ...

  8. 高速在MyEclipse中打开jsp类型的文件

    MyEclipse打开jsp时老是要等上好几秒,嗯嗯,这个问题的确非常烦人,事实上都是MyEclipse的"自作聪明"的结果(它默认用Visual Designer来打开的),进行 ...

  9. Go语言实战_自己定义OrderedMap

    一. 自己定义OrderedMap 在Go语言中.字典类型的元素值的迭代顺序是不确定的.想要实现有固定顺序的Map就须要让自己定义的 OrderedMap 实现 sort.Interface 接口类型 ...

  10. POJ 1562 Oil Deposits (HDU 1241 ZOJ 1562) DFS

    现在,又可以和她没心没肺的开着玩笑,感觉真好. 思念,是一种后知后觉的痛. 她说,今后做好朋友吧,说这句话的时候都没感觉.. 我想我该恨我自己,肆无忌惮的把她带进我的梦,当成了梦的主角. 梦醒之后总是 ...