java+ jsp+js 实现富文本编辑和上传图片功能

java+ jsp+js 实现富文本编辑和上传图片功能

jsp中的引入相关的css js文件

<!---引入kindeditor的样式文件-->
    <link rel="stylesheet" href="../kindeditor/plugins/code/prettify.css" />
    <link rel="stylesheet" href="../kindeditor/themes/default/default.css" />

 <%--富文本编辑 js文件--%>
    <script charset="utf-8" src="../kindeditor/kindeditor-all.js"></script>
    <script charset="utf-8" src="../kindeditor/kindeditor-all-min.js"></script>
    <script charset="utf-8" src="../kindeditor/lang/zh-CN.js"></script>
    <script charset="utf-8" src="../kindeditor/plugins/code/prettify.js"></script>

js代码块

         var KE;
            KindEditor.ready(function(K) {
                KE = K.create("textarea[id='editor']", {
                    allowUpload : true,
                    urlType : 'domain',//relative为相对路径,absolute为绝对路径,domain为带域名的绝对路径
//                  allowFileManager:true, //允许对上传图片进行管理
                    allowPreviewEmoticons : false,//
                    allowFileManager : true, //浏览图片空间
                    allowImageUpload: true, //多图上传。允许上传图片
                    imageTabIndex : 1, //点击上传图片按钮默认显示标签,1为本地上传,默认为0网络图片
                    allowImageRemote: false,//指定不能网络图片
                    filterMode : false, //HTML特殊代码过滤,不会过滤HTML代码
                    resizeType : 1,  //文本框不可拖动
                    cssPath :项目路径+'/kindeditor/plugins/code/prettify.css',
                    uploadJson :项目路径+'/fileouterupload/fileUpload.do',//上传图片到Java逻辑地址
                afterCreate : function() {
                this.sync();
             },
             afterBlur : function() {
                   this.sync();
               },
                    afterBlur: function(){ this.sync(); }, //编辑器失去焦点(blur)时执行的回调函数(将编辑器的HTML数据同步到textarea)
                //    afterUpload : function(url, data, name) { //上传文件后执行的回调函数,必须为3个参数
                //        if(name=="image" || name=="multiimage"){ //单个和批量上传图片时
                //            if(K("#pic").length>0){ //文本框存在
                //                document.getElementById('piclist').options[document.getElementById('piclist').length]=new Option(url,url); //下拉列表框增加一条
                //                document.getElementById('piclist').selectedIndex+=1; //选定刚新增的这一条
                //                K("#indexpicimg").html("<img src='" + url + "' width='100px' height='100px' />"); //重置图片展示区DIV的HTML内容
                //                K("#pic").val(url); //重置文本框值
                //        }
                //    }
                //},
            });
                //KE.get
            prettyPrint();
        });

java逻辑代码


import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
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 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.*;

/**
 * kindeditor编辑器控制部分
 */
@Controller
@RequestMapping("/fileouterupload")
public class FileManageActionController extends BaseAction
{
    // windows
    private String PATH_LINEs = "\\";
    // linux
    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(value = "imgFile", required = false) MultipartFile[] imgFile ) {
        try {
            response.setCharacterEncoding("utf-8");
            PrintWriter out = response.getWriter();
             //文件保存本地目录路径
                String savePath = MapCacheManager.getInstance().getMapCache().get("serverPathUp");
                String serverPicPath = savePath + "/" + "pic"+ "/";
            //文件保存目录URL
                String saveUrls =MapCacheManager.getInstance().getMapCache().get("serverPaths");
                String saveUrlPath = saveUrls + "/" + "upload"+ "/";
                if(!ServletFileUpload.isMultipartContent(request)){
                out.print(getError("请选择文件。"));
                out.close();
                return;
            }
            //检查目录
            File uploadDir = new File(serverPicPath);
            if(!uploadDir.isDirectory()){
                out.print(getError("上传目录不存在。"));
                out.close();
                return;
            }
            //检查目录写权限
            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;
            }
            //创建文件夹
            serverPicPath += dirName + PATH_LINE;
           saveUrlPath+= dirName + PATH_LINE;
            File saveDirFile = new File(serverPicPath);
            if (!saveDirFile.exists()) {
                saveDirFile.mkdirs();
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String ymd = sdf.format(new Date());
            serverPicPath += ymd + PATH_LINE;
           saveUrlPath += ymd + PATH_LINE;
            File dirFile = new File(serverPicPath);
            if (!dirFile.exists()) {
                dirFile.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)){
                    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(serverPicPath, newFileName);
                }catch(Exception e){
                    out.print(getError("上传文件失败。"));
                    out.close();
                    return;
                }
                System.out.println(saveUrlPath+newFileName);
                JSONObject obj = new JSONObject();
                obj.put("error", 0);
                obj.put("url", saveUrlPath + newFileName);
                System.out.println(newFileName+"上传的图片");
                out.print(obj.toJSONString());
                out.close();
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            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;
    }
}

图片保存路径配置

serverPathUp=/opt/data/html/upload/(访问路径)
serverPaths=http://ip地址:端口号

  • 1
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小冷coding

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值