T1358696550
舊歡如夢
2017-02-28 06:33
采纳率: 57.1%
浏览 14.2k
已采纳

kindeditor成功上传图片后,在富文本框内无法正常显示

我直接下载的demo,用servlet改写了jsp,没有问题,但是现在用springboot,就出现了这种问题。
不废话,直接上代码,恳请各位大神的指导:
html:

    <link rel="stylesheet" href="/kindeditor-master/themes/default/default.css" />
    <link rel="stylesheet" href="/kindeditor-master/plugins/code/prettify.css" />
    <script charset="utf-8" src="/kindeditor-master/kindeditor-all.js"></script>
    <script charset="utf-8" src="/kindeditor-master/lang/zh-CN.js"></script>
    <script charset="utf-8" src="/kindeditor-master/plugins/code/prettify.js"></script>
    <script>

        KindEditor.ready(function(K) {
            K.create('textarea[name="content1"]', {
                cssPath : '/kindeditor-master/plugins/code/prettify.css',
                uploadJson : '/kindEditor/upLoad',
                fileManagerJson : '/kindEditor/Manager',
                allowFileManager : true,//是否允许浏览服务器上传文件
                //resizeType : 0,是否可改变编辑器大小0不可以,1可改高度,2都可以。默认为2
                afterCreate : function(msg) {
                    var self = this;
                    K.ctrl(document, 13, function() {
                        self.sync();
                        document.forms['example'].submit();
                    });
                    K.ctrl(self.edit.doc, 13, function() {
                        self.sync();
                        document.forms['example'].submit();
                    });
                }
            });
            prettyPrint();
        });
    </script>

这是文件上传类:



@Controller  
@RequestMapping("/kindEditor")
public class UpLoadJsonAction {

    @RequestMapping("/upLoad")
    public void upLoadImage(HttpServletRequest request, HttpServletResponse response){
        try {       
            PrintWriter out = response.getWriter();


            //文件保存目录路径
            String savePath = request.getRealPath("/") + "attached/";

            //文件保存目录URL
            String saveUrl  = request.getContextPath() + "/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 = 1000000;

            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;
            }

            String dirName = request.getParameter("dir");
            if (dirName == null) {
                dirName = "image";
            }
            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();
            }

            //创建一个DiskFileItemFactory工厂
            FileItemFactory factory = new DiskFileItemFactory();
            //创建一个文件上传解析器
            ServletFileUpload upload = new ServletFileUpload(factory);
            //设置编码
            upload.setHeaderEncoding("UTF-8");
//          //判断提交上来的数据是否是上传表单的数据
//          if(!ServletFileUpload.isMultipartContent(request)){
//          //按照传统方式获取数据
//          return;
//          }
            //判断提交上来的是list数据
//          
            List items = upload.parseRequest(request);
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            Iterator item = multipartRequest.getFileNames();
//          Iterator itr = items.iterator();

            while (item.hasNext()) {
                String fileName = (String) item.next();

                MultipartFile file = multipartRequest.getFile(fileName);


                // 检查文件大小

                if (file.getSize() > maxSize) {
                    out.println(getError("上传文件大小超过限制。"));
                    return;
                }

                // 检查扩展名

                String fileExt = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1).toLowerCase();

                if (!Arrays. 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;
                    try {
                    File uploadedFile = new File(savePath, newFileName);
                    ByteStreams.copy(file.getInputStream(), new FileOutputStream(uploadedFile));
                    } catch (Exception e) {
                    }
                    JSONObject obj = new JSONObject();
                    obj.put("error", 0);
                    obj.put("url", saveUrl + newFileName);
                    out.println(obj.toJSONString());
                }
        } catch (Exception e) {
            e.printStackTrace();
        }


}

    //上传报错的提示方法
    private String getError(String message) {
        JSONObject obj = new JSONObject();
        obj.put("error", 1);
        obj.put("message", message);
        return obj.toJSONString();
    }


}

这是文件管理类:

@Controller 
@RequestMapping("/kindEditor")
public class FileManagerJsonAction {

    @RequestMapping("/Manager")
    public void fileManager(HttpServletRequest request, HttpServletResponse response){
        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        //根目录路径
        String rootPath = request.getRealPath("/") + "attached/";
        //根目录URL,可以指定绝对路径,比如 http://www.yoursite.com/attached/
        String rootUrl  = request.getContextPath() + "/attached/";
        //图片扩展名
        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.println("无效的目录");
                return;
            }
            rootPath += dirName + "/";
            rootUrl += dirName + "/";
            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("/") >= 0 ? str.substring(0, str.lastIndexOf("/") + 1) : "";
        }

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

        //不允许使用..移动到上一级目录
        if (path.indexOf("..") >= 0) {
            out.println("Access is not allowed.");
            return;
        }
        //最后一个字符不是/
        if (!"".equals(path) && !path.endsWith("/")) {
            out.println("Parameter is not valid.");
            return;
        }
        //目录不存在或不是目录
        File currentPathFile = new File(currentPath);
        if(!currentPathFile.isDirectory()){
            out.println("Directory does not exist.");
            return;
        }

        //遍历目录取的文件信息
        List<Hashtable> fileList = new ArrayList<Hashtable>();
        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);

        response.setContentType("application/json; charset=UTF-8");
        out.println(result.toJSONString());



    }
}

正常的效果应该是上传完图片后在富文本框内也是正常显示图片。现在可以上传,但是富文本框内的图片无法正常显示。在文件管理里面,可以找到相应的文件夹或者图片,但是图片也无法正常显示。

结果如下:
图片说明
图片说明

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

4条回答 默认 最新

  • showbo
    已采纳

    返回的路径不对。。自己f12打开浏览器开发工具看图片路径就知道了,肯定是404了

    自己讲服务器改为的路径改为绝对路径,如从根目录开始的路径 /upload/xxx.jpg或者加上域名,记得调整路径

    点赞 评论
  • HackAge4619

    有内容了显示不正常,应该是上传后的图片格式不对

    点赞 评论
  • wjp520120
    wjp520120 2017-12-08 14:32

    很感谢你,在这里帮我解决了案例中这种:List items = upload.parseRequest(request)写法一直获取不到上传文件的问题。
    通过你的写法成功了,谢谢你。

    点赞 评论
  • weixin_43540814
    业业 2021-04-20 14:36

    问题解决了吗

    点赞 评论

相关推荐