KindEditor实现上传图片与回显

本博客前面还有一个简化版容易理解:https://blog.csdn.net/Strive279/article/details/121250542
1.自定义编辑器

// 创建编辑器
    editor = KindEditor.create( "#editor_id", {
    
    
        resizeType : 1,
        allowImageUpload:true,//允许上传图片
        allowFileManager:true, //允许对上传图片进行管理
        uploadJson:root + '/fileUpload',
        filePostName: 'imgFile',// name属性默认值
        fileManagerJson:root + '/fileManager',
        afterChange:function(){
    
    this.sync();},
        afterUpload: function(){
    
    this.sync();}, //图片上传后,将上传内容同步到textarea中
        afterBlur: function(){
    
    this.sync();},   失去焦点时,将上传内容同步到textarea中
        afterCreate : function() {
    
     this.sync();   },
        afterBlur:function(){
    
      this.sync(); },
        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',
            'table', 'hr', 'emoticons', 'baidumap', 'pagebreak',
            'anchor', 'link', 'unlink'],
        allowFileManager: true
    });

2.Java实现代码

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class KindEditorUpload{
    
    
	private String PATH_LINE = "/";

    /**
     * 文件上传
     *
     * @param request  {@link HttpServletRequest}
     * @param response {@link HttpServletResponse}
     * @return json response
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
    @ResponseBody
    public void fileUpload(HttpServletRequest request, HttpServletResponse response,
                           @RequestParam("imgFile") MultipartFile[] imgFile) {
    
    
        try {
    
    
            response.setCharacterEncoding("utf-8");
            PrintWriter out = response.getWriter();

            // 文件保存本地目录路径
            String savePath = PathConfig.temporaryFilePath + PathConfig.imgPath;
            // 文件保存目录URL
            String saveUrl = request.getContextPath() + "/KindEditor/uploads/";
            System.out.println("savePath----------------->" + savePath);
            System.out.println("saveUrl----------------->" + saveUrl);

            if (!ServletFileUpload.isMultipartContent(request)) {
    
    
                out.print(getError("请选择文件。"));
                out.close();
                return;
            }
            // 检查目录
            File uploadDir = new File(savePath);
//            if (!uploadDir.isDirectory()) {
    
    
//                out.print(getError("上传目录不存在。"));
//                out.close();
//                return;
//            }
            if (!uploadDir.exists()) {
    
     //如果不存在
                uploadDir.mkdirs(); //创建该文件夹
            }
            // 检查目录写权限
            if (!uploadDir.canWrite()) {
    
    
                out.print(getError("上传目录没有写权限。"));
                out.close();
                return;
            }

            String dirName = request.getParameter("dir");
            if (dirName == null) {
    
    
                dirName = "image";
            }

            // 定义允许上传的文件扩展名
            Map<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,xml,txt,zip,rar,gz,bz2");

            if (!extMap.containsKey(dirName)) {
    
    
                out.print(getError("目录名不正确。"));
                out.close();
                return;
            }
            // 创建文件夹
//            savePath += dirName + PATH_LINE;
//            saveUrl += dirName + PATH_LINE;
            File saveDirFile = new File(savePath);
            if (!saveDirFile.exists()) {
    
    
                saveDirFile.mkdirs();
            }

//	            //最大文件大小
//	            long maxSize = 1000000;

            // 保存文件
            for (MultipartFile iFile : imgFile) {
    
    
                String fileName = iFile.getOriginalFilename();

//	                //检查文件大小
//	                if(iFile.getSize() > maxSize){
    
    
//	                    out.print(getError("上传文件大小超过限制。"));
//	                    out.close();
//	                    return;
//	                }
                // 检查扩展名
                String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                if (!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)) {
    
    
                    // return getError("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。");
                    out.print(getError("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。"));
                    out.close();
                    return;
                }

                SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
                try {
    
    
                    File uploadedFile = new File(savePath, newFileName);

                    // 写入文件
                    FileUtils.copyInputStreamToFile(iFile.getInputStream(), uploadedFile);
                } catch (Exception e) {
    
    
                    out.print(getError("上传文件失败。"));
                    out.close();
                    return;
                }

                JSONObject obj = new JSONObject();
                obj.put("error", 0);
//                obj.put("url", request.getServletContext().getRealPath(saveUrl) + newFileName);
                obj.put("url", "/showImg?imgUrl=" + newFileName);
                out.print(obj.toJSONString());
                out.close();
            }
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
    }

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

    /**
     * @param imgUrl 图片在本地磁盘的位置 如:E:/teacherCompetition/1/images/1.jpg
     * @param request
     * @param response
     */
    @RequestMapping("/showImg")
    public void picToJSP(@RequestParam("imgUrl") String imgUrl, HttpServletRequest request, HttpServletResponse response){
    
    
        FileInputStream in;
        response.setContentType("application/octet-stream;charset=UTF-8");
        try {
    
    
            //图片读取路径
            String basePath = PathConfig.temporaryFilePath + PathConfig.imgPath;

            File file=new File(basePath + imgUrl);
            if(!file.exists())
            {
    
    
                String pattern = "^file:[/]*";
                imgUrl = imgUrl.replaceAll(pattern, "");
                in=new FileInputStream(imgUrl);
            } else {
    
    
                in=new FileInputStream(basePath + imgUrl);
            }
            int i=in.available();
            byte[]data=new byte[i];
            in.read(data);
            in.close();
            //写图片
            OutputStream outputStream=new BufferedOutputStream(response.getOutputStream());
            outputStream.write(data);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
    }

    /**
     * 文件空间
     *
     * @param request  {@link HttpServletRequest}
     * @param response {@link HttpServletResponse}
     * @return json
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/fileManager")
    @ResponseBody
    public void fileManager(HttpServletRequest request, HttpServletResponse response) {
    
    
        try {
    
    
            // 根目录路径,可以指定绝对路径
            String rootPath = PathConfig.temporaryFilePath + PathConfig.imgPath;
            // 根目录URL,可以指定绝对路径,比如 http://www.yoursite.com/attached/
            String rootUrl = PathConfig.temporaryFilePath + "/showImg?imgUrl=";
            System.out.println("rootPath----------------->" + rootPath);
            System.out.println("rootUrl----------------->" + rootUrl);

            response.setContentType("application/json; charset=UTF-8");
            PrintWriter out = response.getWriter();

            // 图片扩展名
            String[] fileTypes = new String[] {
    
     "gif", "jpg", "jpeg", "png", "bmp" };

            String dirName = request.getParameter("dir");
            if (dirName != null) {
    
    
                if (!Arrays.<String>asList(new String[] {
    
     "image", "flash", "media", "file" }).contains(dirName)) {
    
    
                    out.print("无效的文件夹。");
                    out.close();
                    return;
                }
//                rootPath += dirName + PATH_LINE;
//                rootUrl += PATH_LINE;
                File saveDirFile = new File(rootPath);
                if (!saveDirFile.exists()) {
    
    
                    saveDirFile.mkdirs();
                }
            }
            // 根据path参数,设置各路径和URL
            String path = request.getParameter("path") != null ? request.getParameter("path") : "";
            String currentPath = rootPath + path;
            String currentUrl = rootUrl + path;
            String currentDirPath = path;
            String moveupDirPath = "";
            if (!"".equals(path)) {
    
    
                String str = currentDirPath.substring(0, currentDirPath.length() - 1);
                moveupDirPath = str.lastIndexOf(PATH_LINE) >= 0 ? str.substring(0, str.lastIndexOf(PATH_LINE) + 1) : "";
            }

            // 排序形式,name or size or type
            String order = request.getParameter("order") != null ? request.getParameter("order").toLowerCase() : "name";

            // 不允许使用..移动到上一级目录
            if (path.indexOf("..") >= 0) {
    
    
                out.print("访问权限拒绝。");
                out.close();
                return;
            }
            // 最后一个字符不是/
            if (!"".equals(path) && !path.endsWith(PATH_LINE)) {
    
    
                out.print("无效的访问参数验证。");
                out.close();
                return;
            }
            // 目录不存在或不是目录
            File currentPathFile = new File(currentPath);
            if (!currentPathFile.isDirectory()) {
    
    
                out.print("文件夹不存在。");
                out.close();
                return;
            }

            // 遍历目录取的文件信息
            List<Map<String, Object>> fileList = new ArrayList<Map<String, Object>>();
            if (currentPathFile.listFiles() != null) {
    
    
                for (File file : currentPathFile.listFiles()) {
    
    
                    Hashtable<String, Object> hash = new Hashtable<String, Object>();
                    String fileName = file.getName();
                    if (file.isDirectory()) {
    
    
                        hash.put("is_dir", true);
                        hash.put("has_file", (file.listFiles() != null));
                        hash.put("filesize", 0L);
                        hash.put("is_photo", false);
                        hash.put("filetype", "");
                    } else if (file.isFile()) {
    
    
                        String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                        hash.put("is_dir", false);
                        hash.put("has_file", false);
                        hash.put("filesize", file.length());
                        hash.put("is_photo", Arrays.<String>asList(fileTypes).contains(fileExt));
                        hash.put("filetype", fileExt);
                    }
                    hash.put("filename", fileName);
                    hash.put("datetime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(file.lastModified()));
                    fileList.add(hash);
                }
            }

            if ("size".equals(order)) {
    
    
                Collections.sort(fileList, new SizeComparator());
            } else if ("type".equals(order)) {
    
    
                Collections.sort(fileList, new TypeComparator());
            } else {
    
    
                Collections.sort(fileList, new NameComparator());
            }

            JSONObject result = new JSONObject();
            result.put("moveup_dir_path", moveupDirPath);
            result.put("current_dir_path", currentDirPath);
            result.put("current_url", currentUrl);
            result.put("total_count", fileList.size());
            result.put("file_list", fileList);

            out.println(result.toJSONString());
            out.close();
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }

    }
	

pathConfig配置文件

package com.newdo.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class PathConfig {
    
    

    /**路径类型*/
    public static String pathType;

    @Value(value="${path.type}")
    public void setSavePath(String savePath){
    
    
        pathType = savePath;
    }

    /**临时文件存储目录*/
    public static String temporaryFilePath;

    @Value(value="${temporary.filePath}")
    public void setSavePath1(String savePath){
    
    
        temporaryFilePath = savePath;
    }

    /**临时文件存储后续目录*/
    public static String temporaryPath;

    @Value(value="${temporary.Path}")
    public void setSavePath2(String savePath){
    
    
        temporaryPath = savePath;
    }

    /**图片存储目录*/
    public static String imgPath;

    @Value(value="${img.Path}")
    public void setSavePath3(String savePath){
    
    
        imgPath = savePath;
    }
}

application配置文件需要添加的参数

#静态资源
spring.mvc.static-path-pattern=/static/**
spring.resources.static-locations=classpath:/static/

#设置请求大小限制
spring.servlet.multipart.max-file-size=100MB
spring.servlet.multipart.max-request-size=100MB

#路径类型 windows:\\  liunx:/
path.type=\\
#path.type=/

#临时文件存放路径
temporary.filePath=D:\\dxproject\\temporaryFile
temporary.Path=\\resources\\temporaryFile\\
#temporary.filePath=/usr/zhgxrsgl-tomcat
#temporary.Path=/resources/temporaryFile/

#图片存放路径
img.Path=\\KindEditor\\uploads\\
#img.Path=/KindEditor/uploads/

猜你喜欢

转载自blog.csdn.net/Strive279/article/details/121252233