Java实现多文件上传下载,kindeditor富文本保存为word文件,文件列表分页显示

介绍

SpringBoot+Thymeleaf+Mybaits项目部分功能,
实现文件的多文件上传和下载,以及将kindeditor富文本内容保存为.doc文件
文件上传/创建后以列表形式显示,并且可以分页显示

提示

简单记录,仅供参考,代码并不完整,需要简单修改后才能使用(没提供.css文件,需要删除html中的class;另外部分变量通过session获取,可以适当修改)

关键代码

html:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link th:href="@{/css/flow.css}" rel="stylesheet">
    <script type="text/javascript"  th:src="@{/js/flow.js}" ></script>
    <script type="text/javascript" charset="utf-8" th:src="@{/kindeditor/kindeditor.js}"></script>
    <script type="text/javascript" charset="utf-8" th:src="@{/kindeditor/lang/zh_CN.js}"></script>
    <script type="text/javascript" charset="utf-8" th:src="@{/kindeditor/lang/zh_CN.js}"></script>
    <link rel="stylesheet" th:href="@{/kindeditor/themes/default/default.css}" />
    <script type="text/javascript">
        var editor;
        KindEditor.ready(function(K) {
            editor= K.create('#editor_id1', {
                uploadJson : 'kindeditor/jsp/upload_json.jsp',
                fileManagerJson : 'kindeditor/jsp/file_manager_json.jsp',
                allowFileManager : true ,resizeType:0 ,urlType:'domain',
                afterBlur: function(){this.sync();}
            });
        });
    </script>
</head>

<body>
<form  th:action="@{/oa/cfile}" id="cfileid"  name="cfileid" enctype="multipart/form-data" method="post">
    <div style="height: 20px;clear: both;"></div>

    <div style="height: 5px;clear: both;"></div>
    <div class="newwidth" >
        <div class="newflowleft"style="margin-top: 30px" >
            <div class="newlefttable">
                <div class="newrow" style="text-align: center;font-family: 楷体;color: #5b9909;font-weight: bold;">
                    <div style="border-bottom: 1px solid red;width: 400px;font-size: 15px;" >创健工作文件</div>
                </div>
                <div style="clear: both;"></div>
                <div class="newrow">
                    <div class="newrowleft">文件名称:</div>
                    <div class="newrowright">
                        <input type="text" id="cfilename" name="cfilename" placeholder="创建文件请输入文件名" onblur="checkinput('newflowname','newflownamex')" class="commtext">
                        <span id="newflownamex" name="newflownamex" style="font-size: 11px;color:red;"></span>
                    </div>
                </div>
                <div style="clear: both;"></div>
                <div class="newrow" style="height: 60px;">
                    <div class="newrowleft" style="height: 58px;line-height: 58px;vertical-align: middle;">上传word文件:</div>
                    <div class="newrowright" style="height: 58px;">
                        <input type="file"  id="tranfile" multiple name="tranfile" accept="application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel,application/vnd.ms-word"  style="display: none;" onchange="onc()">
                        <textarea style="height: 52px;" id="tranfilex" name="tranfilex" class="commtext" onblur="checkfile('tranfilex')" readonly></textarea>
                        <input type="button" value="选择文件" class="tranbutton" onclick="selectfile('tranfile')">
                    </div>
                </div>

                <div style="clear: both;"></div>
                <div class="newrow" >
                    <div class="newrowleft" style="border-right: 0px;width: 397px;text-align: left;">*文件扼要说明:</div>
                </div>
                <div style="clear: both;"></div>
                <div class="newrow"><textarea style="margin-left: 5px;margin-top: 5px;" cols="52" rows="15" id="fileitr" name="fileitr"></textarea></div>
            </div>
        </div>
        <div class="newflowright" style="border: none" >
            <div class="newrow" style="margin:auto;font-family: 楷体;color: #5b9909;font-weight: bold;width: auto;">
                <div style="border-bottom: 1px solid red;font-size: 15px;float: left;" >文件内容(与上传文件二选一)</div>
            </div>
            <div style="clear: both;height: 5px;"></div>
            <textarea id="editor_id1" name="editor_id1" style="width:100%;height:423px;"></textarea>
        </div>
    </div>
    <div style="float: left;margin-left: 150px;margin-top: 15px">
        <input type="button" value="创建/上传文件" class="flowsbutton" style="width:100px;" onclick="checknewfile()">
        <span style="color: red" th:text="${incident}"></span>
    </div>
    <div style="height: 5px;clear: both;margin-top: 30px"></div>
    <div class="seatile">文件列表</div>
    <div style="height: 5px;clear: both;"></div>
    <div style="clear: both;"></div>
    <div class="fshowline" style="background-color: whitesmoke;">
        <div class="fshowcell" style="width: 50px;">ID</div>
        <div class="fshowcell" style="width: 300px;">文件名称</div>
        <div class="fshowcell"  style="width: 100px">文件后缀</div>
        <div class="fshowcell" style="width: 200px;">存储路径</div>
        <div class="fshowcell" style="width: 150px;">文件大小</div>
        <div class="fshowcell"style="width: 400px;" >文件扼要说明</div>
        <div class="fshowcell" style="width: 200px;">上传时间</div>
        <div class="fshowcell" style="width: 100px;">下载</div>
        <div class="fshowcell" style="width: 100px;">删除</div>
    </div>
    <div style="clear: both;"></div>

    <div th:if="${page.totalRows} == 0">
        <div class="fshowline" style="text-align: center;vertical-align: middle;">
            无文件数据
        </div>
    </div>
    <div th:if="${page.totalRows}  != 0">
        <div th:each="c,state:${files}">
            <div class="fshowline">
                <div class="fshowcell" style="display: none"><span th:text="${c.id}"></span></div>
                <div class="fshowcell" style="width: 50px;"><span th:text="${state.index}+1+(${page.currentPage}-1)*${page.pageSize}"></span></div>
                <div class="fshowcell" style="width: 300px;"><span th:text="${c.oldFileName}"></span></div>
                <div class="fshowcell" style="width: 100px"><span th:text="${c.ext}"></span></div>
                <div class="fshowcell" style="width: 200px;"><span th:text="${c.path}"></span></div>
                <div class="fshowcell" style="width: 150px;"><span th:text="${c.size}"></span>B</div>
                <div class="fshowcell"style="width: 400px;" ><span th:text="${c.fileitr}"></span></div>
                <div class="fshowcell" style="width: 200px;"><span th:text="${c.uploadTime}"></span></div>
                <div class="fshowcell" style="width: 100px;"><a th:href="@{/oa/download(id=${c.id})}">下载</a></div>
                <div class="fshowcell" style="width: 100px;"><a href="javascript:void(0)" th:onclick="delefile([[${c.id}]])">删除</a></div>
            </div>
        </div>
    </div>
    <div style="clear: both;height:2px;border-bottom: 1px solid green;"></div>
    
    <!--换页控制部分-->
    <div style="display: none;"><input type="text" th:value="${page.currentPage}" id="currentpx1" name="currentpx1"></div>
    <div th:if="${page.totalPage}!=1">
        <div class="fshowline">
            <div class="fshowcell" style="width: 160px;text-align: left;font-size: 10px;"><input type="text" id="currentp" name="currentp"  class="currentb"  readonly  th:value="${page.currentPage}" style="width: 7px;border: none;">/<span th:text="${page.totalPage}"></span>,<span th:text="${page.totalRows}"></span>个记录
            </div>
            <div class="fshowcell" style="width:100%;text-align: center;">
            <span title="首页">
            <input type="submit" value="" name="first" id="first" onclick="firstcheck1('currentpx1');" class="firstbutton" style="vertical-align: middle;">
           </span>
                <span title="上一页">
            <input type="submit" value="" name="privious" id="privious" onclick="priviouscheck1('currentpx1');" class="previousbutton" style="vertical-align: middle;">
            </span>
                <span title="下一页">
                <input type="submit" value="" name="next" id="next" th:onclick="nextcheck1('currentpx1',[[${page.totalPage}]]);" class="nextbutton" style="vertical-align: middle;">
            </span>
                <span title="尾页">
                <input type="submit" value="" name="last" id="last" th:onclick="lastcheck1('currentpx1',[[${page.totalPage}]]);" class="lastbutton" style="vertical-align: middle;" >
            </span>
            </div>
        </div>
    </div>
</form>
</body>
</html>

.js文件

function selectfile(sname) {
    document.getElementById(sname).click();
}
function checknewfile() {
    document.cfileid.submit()
}
function delefile(id) {
    if (confirm("删除后无法找回,确认删除?")){
        window.location.href = "../oa/filedelete?id=" + id;
    }
}

Controller层

   @RequestMapping("/cfile")
        private String cfile(MultipartFile[] tranfile,Model model, HttpServletRequest request) throws Exception {
            HttpSession session = request.getSession();
            Long userId = Long.parseLong(session.getAttribute("userId").toString());
            String user = session.getAttribute("loginuser").toString();
            String fileitr = request.getParameter("fileitr");
            String content =  request.getParameter("editor_id1");
            String cfilename = request.getParameter("cfilename");//创建文件名

            String content1 = "<html><head>"+"</head><body>" + content + "</body></html>";
            if (tranfile!=null){

                for (int i=0;i<tranfile.length;i++){

                    UserFile userFile1 = new UserFile();
                    userFile1.setOldFileName(tranfile[i].getOriginalFilename());
                    userFile1.setUserId(userId);
                    if (flowMapper.selectByFileName(userFile1)==null){ //查询文件是否重复上传
                        String oldFileName = tranfile[i].getOriginalFilename();
                        //文件大小
                        Long size = tranfile[i].getSize();
                    //文件类型
                    String type = tranfile[i].getContentType();
                    //获取文件后缀
                    String extension = "." + FilenameUtils.getExtension(tranfile[i].getOriginalFilename());

                    String realPath = ResourceUtils.getURL("D:\\eet").getPath();
                    String dateFormat = new SimpleDateFormat("yyyy-MM-dd").format(new Date());

                    String dateDirPath = realPath +user+ " "+dateFormat ;
                    File dateDir = new File(dateDirPath);
                    if (!dateDir.exists()) dateDir.mkdirs();
                    if (size!=0&&oldFileName!=""){
                        //处理文件上传
                        tranfile[i].transferTo(new File(dateDir,oldFileName));
                        UserFile userFile = new UserFile();
                        userFile.setOldFileName(oldFileName);
                        userFile.setExt(extension);
                        userFile.setSize(String.valueOf(size));
                        userFile.setType(type);
                        userFile.setPath(user+ " "+dateFormat);
                        userFile.setUserId(userId);
                        userFile.setUploadTime(dateFormat);
                        userFile.setFileitr(fileitr);
                        flowMapper.insertFile(userFile);
                    }
                }
                else {
                    model.addAttribute("incident","文件重复上传");
                }
            }

        }

             //创建word文档
            if (content!=null&&content.length()!=0){
                String firstpic = serviceImp.getFirstPic(content);//图片
                //String realPath = ResourceUtils.getURL("D:\\eet").getPath();
                String dateFormat = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
                String path = "D:\\eet\\"+user+" "+dateFormat+"\\";
                File fileDir = new File(path);
                if (!fileDir.exists()) fileDir.mkdirs();
                if (fileDir.exists()) {
                    // 生成临时文件名称
                    if (cfilename!=null&&cfilename.length()!=0){
                        String fileName = cfilename+".doc";
                        byte b[] = content1.getBytes("GBK");

                        ByteArrayInputStream bais = new ByteArrayInputStream(b);

                        POIFSFileSystem poifs = new POIFSFileSystem();
                        DirectoryEntry directory = poifs.getRoot();
                        DocumentEntry documentEntry = directory.createDocument("WordDocument", bais);

                        FileOutputStream ostream = new FileOutputStream(path +fileName);
                        poifs.writeFilesystem(ostream);
                        bais.close();
                        ostream.close();

                        UserFile userFile = new UserFile();
                        userFile.setOldFileName(fileName);
                        userFile.setExt(".doc");
                        int size = documentEntry.getSize();
                        userFile.setSize(String.valueOf(size));
                        userFile.setPath(user+ " "+dateFormat);
                        userFile.setUserId(userId);
                        userFile.setUploadTime(dateFormat);
                        userFile.setFileitr(fileitr);
                        flowMapper.insertFile(userFile);
                    }
                    else {
                        model.addAttribute("创建文件需输入文件名");
                    }

                }
            }



        //----------------------显示文件---------------------
        String pageID=request.getParameter("currentpx1");
        Page page = new Page();
        page.setUserId(userId);
        page.setStartRow(0);
        page.setPageSize(2100000000);

        List<UserFile> ff = flowMapper.findByuserId(page);
        page.setTotalRows(ff.size());
        page.setPageSize(10);
        page.setTotalPage(serviceImp.qTotalPage(page));
        if (pageID == null){
            int pageId = 1;
            page.setCurrentPage(pageId);
        }
        else {
            int pageId = Integer.parseInt(pageID);
            page.setCurrentPage(pageId);
        }
        page.setStartRow(serviceImp.qStartRow(page));
        ff = flowMapper.findByuserId(page);
        model.addAttribute("files",ff);
        model.addAttribute("page",page);


        return "cfile";
    }
        //---------文件下载
    @RequestMapping("/download")
    private String download(String openStyle,String id,HttpServletRequest request,HttpServletResponse response,Model model) throws IOException{
        HttpSession session = request.getSession();
        Long userId = Long.parseLong(session.getAttribute("userId").toString());
        Long Id = Long.parseLong(id);
        //获取打开方式
        openStyle = openStyle == null ? "attachment" : openStyle;
        System.out.println(Id);
        //获取文件信息
        UserFile userFile = flowMapper.selectById(Id);
        //根据文件信息中文件名字 和 文件存储路径获取文件输入流
        String realpath = ResourceUtils.getURL("D:\\eet\\").getPath() + userFile.getPath();
        //获取文件输入流
        FileInputStream is = new FileInputStream(new File(realpath, userFile.getOldFileName()));
        //附件下载
        response.setHeader("content-disposition", openStyle + ";fileName=" + URLEncoder.encode(userFile.getOldFileName(), "UTF-8"));
        //获取响应输出流
        ServletOutputStream os = response.getOutputStream();
        //文件拷贝
        IOUtils.copy(is, os);
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(os);


        //----------------------显示文件---------------------
        String pageID=request.getParameter("currentpx1");
        Page page = new Page();
        page.setUserId(userId);
        page.setStartRow(0);
        page.setPageSize(2100000000);

        List<UserFile> ff = flowMapper.findByuserId(page);
        page.setTotalRows(ff.size());
        page.setPageSize(10);
        page.setTotalPage(serviceImp.qTotalPage(page));
        if (pageID == null){
            int pageId = 1;
            page.setCurrentPage(pageId);
        }
        else {
            int pageId = Integer.parseInt(pageID);
            page.setCurrentPage(pageId);
        }
        page.setStartRow(serviceImp.qStartRow(page));
        ff = flowMapper.findByuserId(page);
        model.addAttribute("files",ff);
        model.addAttribute("page",page);

        return "upfile";
    }
       @RequestMapping("/filedelete")
    private String filedelete (String id,HttpServletRequest request,Model model)throws IOException{
        HttpSession session = request.getSession();
        Long userId = Long.parseLong(session.getAttribute("userId").toString());
        Long Id = Long.parseLong(id);

        //=================删除文件================
        //根据id查询信息
        UserFile userFile = flowMapper.selectById(Id);
        System.out.println(userFile.getPath());
        //删除文件
//        realPath绝对路径
        String realPath = ResourceUtils.getURL("D:\\eet\\").getPath()+ userFile.getPath();
        System.out.println(realPath);
        File file = new File(realPath, userFile.getOldFileName());
        if(file.exists()){
            file.delete();//立即删除
            flowMapper.deleFile(Id);
        }

        //----------------------显示文件---------------------
        String pageID=request.getParameter("currentpx1");
        Page page = new Page();
        page.setUserId(userId);
        page.setStartRow(0);
        page.setPageSize(2100000000);

        List<UserFile> ff = flowMapper.findByuserId(page);
        page.setTotalRows(ff.size());
        page.setPageSize(10);
        page.setTotalPage(serviceImp.qTotalPage(page));
        if (pageID == null){
            int pageId = 1;
            page.setCurrentPage(pageId);
        }
        else {
            int pageId = Integer.parseInt(pageID);
            page.setCurrentPage(pageId);
        }
        page.setStartRow(serviceImp.qStartRow(page));
        ff = flowMapper.findByuserId(page);
        model.addAttribute("files",ff);
        model.addAttribute("page",page);
        return "cfile";
    }

Model(UserFile和Page两个类)

//UserFile类,存储文件信息
public class UserFile {
    private Long id;
    private String oldFileName;
    private String ext;
    private String path;
    private String size;
    private String type;
    private String isImg;
    private Integer downcounts;
    private String uploadTime;
    private Long userId;
    private String fileitr;
    //get、set方法省略
}

//Page类,用于分页
public class Page {
    //开始行,根据页面的值计算,调用对应的服务函数
    private Integer startRow;
    //每页的行数,直接指定
    private Integer pageSize;
    //当前页码,来自页面
    private Integer currentPage;
    //总页码,根据总行数计算
    private Integer totalPage;
    //根据数据库查询获得
    private Integer totalRows;
    //模糊搜索同类的条件
    private String condition;
    //企业编号,通过session获取
    private Long firmId;
    //用户ID
    private Long userId;
   //get、se方法省略
   }

Service层(包含了分页计算的方法)

@Service
public class ServiceImp {
   //实现分页
    public int qTotalPage(Page page){
        int totalPage=0;
        int totalRow=page.getTotalRows();
        int pageSize=page.getPageSize();
        if(totalRow!=0){
            int remainder=totalRow%pageSize;

            if(remainder==0){
                totalPage=totalRow/pageSize;
            }
            else{
                totalPage=totalRow/pageSize+1;
            }}
        else{totalPage=1;}
        return totalPage;
    }
    //分页后开始行
    public Integer qStartRow(Page page){
        int startRow=0;
        int currentPage=page.getCurrentPage();
        //int totalRow=page.getTotalRows();
       int pageSize=page.getPageSize();
        startRow=(currentPage-1)*pageSize;

        return startRow;
    }
  }

Dao层

    //按文件名搜索文件信息
    public UserFile selectByFileName(UserFile userFile);
    //根据id获取文件信息
    public UserFile selectById(Long id);
    //保存上传文件信息
    public void insertFile(UserFile userFile);
    //根据userid获取文件信息
    public List<UserFile> findByuserId(Page page);
    //删除文件信息
    public void deleFile(Long id);

Mapper

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.hz.dao.flowMapper">
    <!--文件表-->
    <resultMap id="baseFile" type="com.hz.model.UserFile">
        <result column="id" jdbcType="BIGINT" property="id"/>
        <result column="oldFileName" jdbcType="VARCHAR" property="oldFileName"/>
        <result column="ext" jdbcType="VARCHAR" property="ext"/>
        <result column="path" jdbcType="VARCHAR" property="path"/>
        <result column="size" jdbcType="VARCHAR" property="size"/>
        <result column="type" jdbcType="VARCHAR" property="type"/>
        <result column="isImg" jdbcType="VARCHAR" property="isImg"/>
        <result column="uploadTime" jdbcType="VARCHAR" property="uploadTime"/>
        <result column="userId" jdbcType="BIGINT" property="userId"/>
        <result column="fileitr" jdbcType="VARCHAR" property="fileitr"/>
    </resultMap>
    <!--按文件名搜索文件信息-->
    <select id="selectByFileName" resultMap="baseFile">
        select *
        from t_files
        where oldFileName=#{oldFileName,jdbcType=VARCHAR}
              and userId = #{userId,jdbcType=VARCHAR}
    </select>
        <!--根据id获取文件信息-->
    <select id="selectById"  resultMap="baseFile">
        select *
        from t_files
        where id = #{id}
    </select>
        <!--保存上传文件信息-->
    <insert id="insertFile" parameterType="com.hz.model.UserFile">
        insert into t_files
        <trim prefix="(" suffix=")" suffixOverrides=","  >
            <if test="oldFileName != null">
                oldFileName,
            </if>
            <if test="ext != null">
                ext,
            </if>
            <if test="size != null">
                size,
            </if>
            <if test="path != null">
                path,
            </if>
            <if test="type != null">
                type,
            </if>
            <if test="isImg != null">
                isImg,
            </if>
            <if test="uploadTime != null">
                uploadTime,
            </if>
            <if test="userId != null">
                userId,
            </if>
            <if test="fileitr != null">
                fileitr,
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="oldFileName != null">
                #{oldFileName,jdbcType=VARCHAR},
            </if>
            <if test="ext != null">
                #{ext,jdbcType=VARCHAR},
            </if>
            <if test="size != null">
                #{size,jdbcType=VARCHAR},
            </if>
            <if test="path != null">
                #{path,jdbcType=VARCHAR},
            </if>
            <if test="type != null">
                #{type,jdbcType=VARCHAR},
            </if>
            <if test="isImg != null">
                #{isImg,jdbcType=VARCHAR},
            </if>
            <if test="uploadTime != null">
                #{uploadTime,jdbcType=VARCHAR},
            </if>
            <if test="userId != null">
                #{userId,jdbcType=BIGINT},
            </if>
            <if test="fileitr != null">
                #{fileitr,jdbcType=VARCHAR}
            </if>
        </trim>
    </insert>
    <!--删除文件-->
    <delete id="deleFile"  >
        delete from t_files
        where id=#{id,jdbcType=BIGINT}
    </delete>
        <!--根据userid获取文件信息-->
    <select id="findByuserId"  resultMap="baseFile" resultType="com.hz.model.UserFile" parameterType="com.hz.model.Page">
        select *
        from t_files
        where userId = #{userId}
        order by id desc
        limit #{startRow},#{pageSize}
    </select>
</mapper>

Mysql

DROP TABLE IF EXISTS `t_files`;
CREATE TABLE `t_files` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `oldFileName` varchar(255) DEFAULT NULL,
  `ext` varchar(50) DEFAULT NULL,
  `path` varchar(255) DEFAULT NULL,
  `size` varchar(255) DEFAULT NULL,
  `type` varchar(255) DEFAULT NULL,
  `uploadTime` varchar(255) DEFAULT NULL,
  `userId` int(11) DEFAULT NULL,
  `fileitr` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=40 DEFAULT CHARSET=utf8;

效果图

在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
首先,我们需要在 Spring Boot 项目中引入 kindeditor 的相关依赖。可以通过在 Maven 或 Gradle 配置文件中添加以下依赖来实现: Maven: ```xml <dependency> <groupId>com.github.kindeditor</groupId> <artifactId>kindeditor</artifactId> <version>4.1.11</version> </dependency> ``` Gradle: ```groovy compile group: 'com.github.kindeditor', name: 'kindeditor', version: '4.1.11' ``` 接着,在 Spring Boot 项目中添加一个控制器,用于处理 kindeditor 的上传请求和获取文件列表请求。示例代码如下: ```java @RestController @RequestMapping("/kindeditor") public class KindEditorController { @Autowired private Environment env; /** * KindEditor上传文件接口 * @param file * @param request * @return */ @PostMapping("/upload") public Map<String, Object> upload(@RequestParam("imgFile") MultipartFile file, HttpServletRequest request) { Map<String, Object> result = new HashMap<>(); String url = ""; try { // 获取上传文件目录 String uploadDir = env.getProperty("kindeditor.upload-dir"); if (StringUtils.isBlank(uploadDir)) { uploadDir = request.getServletContext().getRealPath("/upload"); } File dir = new File(uploadDir); if (!dir.exists()) { dir.mkdirs(); } // 获取上传文件名 String fileName = file.getOriginalFilename(); // 生成新的文件名 String newFileName = UUID.randomUUID().toString() + "." + StringUtils.substringAfterLast(fileName, "."); // 保存文件 File dest = new File(dir, newFileName); file.transferTo(dest); // 返回文件访问URL url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/upload/" + newFileName; result.put("error", 0); result.put("url", url); } catch (Exception e) { result.put("error", 1); result.put("message", "文件上传失败"); } return result; } /** * KindEditor获取文件列表接口 * @param request * @return */ @GetMapping("/filemanager") public Map<String, Object> fileManager(HttpServletRequest request) { Map<String, Object> result = new HashMap<>(); try { // 获取上传文件目录 String uploadDir = env.getProperty("kindeditor.upload-dir"); if (StringUtils.isBlank(uploadDir)) { uploadDir = request.getServletContext().getRealPath("/upload"); } File dir = new File(uploadDir); if (!dir.exists()) { dir.mkdirs(); } // 遍历目录,获取文件列表 List<Map<String, Object>> fileList = new ArrayList<>(); File[] files = dir.listFiles(); if (files != null && files.length > 0) { for (File file : files) { Map<String, Object> fileInfo = new HashMap<>(); fileInfo.put("is_dir", file.isDirectory()); fileInfo.put("has_file", file.isFile()); fileInfo.put("filesize", file.length()); fileInfo.put("filename", file.getName()); fileInfo.put("datetime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(file.lastModified()))); fileList.add(fileInfo); } } result.put("error", 0); result.put("file_list", fileList); } catch (Exception e) { result.put("error", 1); result.put("message", "文件列表获取失败"); } return result; } } ``` 其中,`upload` 方法用于处理 kindeditor 的上传请求,`filemanager` 方法用于获取文件列表请求。在 `upload` 方法中,我们通过 `MultipartFile` 接口获取上传的文件信息,然后将文件保存至指定目录,并返回文件访问 URL。在 `filemanager` 方法中,我们遍历指定目录下的所有文件,并将文件信息封装成列表返回。 最后,在前端页面中引入 kindeditor 的相关资源文件,并在页面中添加文本编辑器元素。示例代码如下: ```html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>KindEditor富文本编辑器</title> <link rel="stylesheet" href="http://cdn.staticfile.org/kindeditor/4.1.11/themes/default/default.css" /> <script src="http://cdn.staticfile.org/kindeditor/4.1.11/kindeditor.js"></script> <script src="http://cdn.staticfile.org/kindeditor/4.1.11/lang/zh-CN.js"></script> </head> <body> <textarea id="editor"></textarea> <script> KindEditor.ready(function(K) { K.create('#editor', { uploadJson: '/kindeditor/upload', fileManagerJson: '/kindeditor/filemanager' }); }); </script> </body> </html> ``` 在以上代码中,我们引入了 kindeditor 的相关资源文件,并在页面中添加了一个 ID 为 `editor` 的 textarea 元素,然后通过 JavaScript 代码初始化了 kindeditor,并设置了上传文件和获取文件列表的 URL。 至此,我们就可以在 Spring Boot 项目中轻松实现 kindeditor富文本编辑器功能了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值