使用场景:  本人用了人人开源Vue(2.X)前端  ueditor入坑.  一步步时间图片回显,   废话不多说

第一步:  下载GitHub源码地址:
https://github.com/fex-team/ueditor/tree/v1.4.3.3
注意: 下载后缺少ueditor.all.js  文件.. 后期需要改变此代码

第二步:  cmd 进入下载文件目录

>npm install -g grunt-cli              #安装grunt
>npm install                                #初始化 前端需要node,npm环境
>grunt                                         # 看见Done. without errors 就表示成功

 

 

 注意: 此时在ueditor-1.4.3.3目录有一个dist目录。进去看到ueditor.all.js

 

 

 

第三步: 前端部分VUE改变.

拷贝ueditor.all.js到static/plugins/ueditor-1.4.3.3目录,  同时修改index.html的引用

 

ueditor.config.js修改

添加一行 window.UEDITOR_HOME_URL = "/static/plugins/ueditor-1.4.3.3/";

 

 

 

子组件 product-ueditor.vue

<template>
  <div class="mod-demo-ueditor">
    <script :id="ueId" class="ueditor-box" type="text/plain" style="width: 100%; height: 260px;">{{value}}</script>
    <!-- 获取内容 -->
    <p><el-button @click="showContent()">获得内容</el-button></p>
    <el-dialog
      title="内容"
      :visible.sync="dialogVisible"
      :append-to-body="true">
      {{ ueContent }}
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import ueditor from 'ueditor'
  export default {
    data () {
      return {
        // 富文本初始值
        value: '',
        // 富文本
        ue: null,
        ueId: `J_ueditorBox_${new Date().getTime()}`,
        ueContent: '',
        dialogVisible: false
      }
    },
    mounted () {
      this.ue = ueditor.getEditor(this.ueId, {
        toolbars: [[
          'anchor', // 锚点
          'undo', // 撤销
          'redo', // 重做
          'bold', // 加粗
          'indent', // 首行缩进
          // 'snapscreen', // 截图, 需要下载ueditor截图插件
          'italic', // 斜体
          'underline', // 下划线
          'strikethrough', // 删除线
          'subscript', // 下标
          'fontborder', // 字符边框
          'superscript', // 上标
          'formatmatch', // 格式刷
          // 'source', // 源代码
          // 'blockquote', // 引用
          'pasteplain', // 纯文本粘贴模式
          'selectall', // 全选
          // 'print', // 打印
          'preview', // 预览
          'horizontal', // 分隔线
          // 'removeformat', // 清除格式
          'date', // 日期
          'time', // 时间
          // 'insertrow', // 前插入行
          // 'insertcol', // 前插入列
          // 'mergeright', // 右合并单元格
          // 'mergedown', // 下合并单元格
          'deleterow', // 删除行
          'deletecol', // 删除列
          // 'splittorows', // 拆分成行
          // 'splittocols', // 拆分成列
          // 'splittocells', // 完全拆分单元格
          // 'deletecaption', // 删除表格标题
          // 'inserttitle', // 插入标题
          // 'mergecells', // 合并多个单元格
          'deletetable', // 删除表格
          'cleardoc', // 清空文档
          // 'insertparagraphbeforetable', // "表格前插入行"
          // 'insertcode', // 代码语言
          'fontfamily', // 字体
          'fontsize', // 字号
          'paragraph', // 段落格式
          'simpleupload', // 单图上传
          'insertimage', // 多图上传
          // 'edittable', // 表格属性
          // 'edittd', // 单元格属性
          'link', // 超链接
          'unlink', // 取消链接
          'emotion', // 表情
          'spechars', // 特殊字符
          // 'searchreplace', // 查询替换
          // 'map', // Baidu地图
          // 'gmap', // Google地图
          // 'insertvideo', // 视频
          // 'help', // 帮助
          'justifyleft', // 居左对齐
          'justifyright', // 居右对齐
          'justifycenter', // 居中对齐
          'justifyjustify', // 两端对齐
          'forecolor', // 字体颜色
          // 'backcolor', // 背景色
          'insertorderedlist', // 有序列表
          'insertunorderedlist', // 无序列表
          'fullscreen', // 全屏
          'directionalityltr', // 从左向右输入
          'directionalityrtl', // 从右向左输入
          // 'rowspacingtop', // 段前距
          // 'rowspacingbottom', // 段后距
          'pagebreak', // 分页
          'insertframe', // 插入Iframe
          'imagenone', // 默认
          // 'imageleft', // 左浮动
          // 'imageright', // 右浮动
          // 'attachment', // 附件
          'imagecenter', // 居中
          // 'wordimage', // 图片转存
          'lineheight', // 行间距
          'edittip ', // 编辑提示
          'customstyle', // 自定义标题
          'autotypeset', // 自动排版
          // 'webapp', // 百度应用
          // 'touppercase', // 字母大写
          // 'tolowercase', // 字母小写
          'background', // 背景
          // 'template', // 模板
          'scrawl', // 涂鸦
          // 'music', // 音乐
          'inserttable', // 插入表格
          // 'drafts', //  从草稿箱加载
          'charts' // 图表
        ]],
        serverUrl: this.$http.adornUrl(`/ueditor/config`), // 服务器统一请求接口路径
        zIndex: 3000
      })
    },
    destroyed () {
      this.ue.destroy()
    },
    methods: {
      init (value) {
        this.ue.ready(() => {
          this.ue.setContent(value)
        })
      },
      showContent () {
        this.dialogVisible = true
        this.ue.ready(() => {
          this.ueContent = this.ue.getContent()
        })
      },
      getContent () {
        return new Promise((resolve, reject) => {
          this.ue.ready(() => {
            this.ueContent = this.ue.getContent()
            resolve(this.ueContent)
          })
        })
      }
    }
  }
</script>

<style lang="scss">
  .mod-demo-ueditor {
    position: relative;
    z-index: 510;
    > .el-alert {
      margin-bottom: 10px;
    }
  }
</style>
View Code

注意: 修改serverUrl, 和显示的功能图标

this.ue = ueditor.getEditor(this.ueId, {
        toolbars: 显示的图片,自己定义,
        serverUrl: this.$http.adornUrl(`/ueditor/config`), // 服务器统一请求接口路径 请求的Spring Boot后台地址
        zIndex: 3000
      })

 

 

 

父组件使用,VUE都懂的,不写太长了

<product-ueditor ref="refProductUeditor" ></product-ueditor>

import ProductUeditor from './product-ueditor'
components: {
ProductUeditor
}
// API初始化内容
this.$refs.refProductUeditor.init('测试内容')

// API显示内容
this.$refs.refProductUeditor.showContent()

  

 第四部: 后端Spring Boot

本人参考了: https://blog.csdn.net/kshon/article/details/102674154..   

resource/ueditor/config.josn 配置文件移入   在ueditor-1.4.3.3\jsp目录中有config.json. 移入时会出错.本人已将注释去掉.

 

 

 

{
  "imageActionName": "uploadimage",
  "imageFieldName": "upfile",
  "imageMaxSize": 2048000,
  "imageAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"],
  "imageCompressEnable": true,
  "imageCompressBorder": 1600,
  "imageInsertAlign": "none",
  "imageUrlPrefix": "",
  "imagePathFormat": "/ueditor/{time}/{filename}",
  "scrawlActionName": "uploadscrawl",
  "scrawlFieldName": "upfile",
  "scrawlPathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}",
  "scrawlMaxSize": 2048000,
  "scrawlUrlPrefix": "",
  "scrawlInsertAlign": "none",
  "snapscreenActionName": "uploadimage",
  "snapscreenPathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}",
  "snapscreenUrlPrefix": "",
  "snapscreenInsertAlign": "none",
  "catcherLocalDomain": ["127.0.0.1", "localhost", "img.baidu.com"],
  "catcherActionName": "catchimage",
  "catcherFieldName": "source",
  "catcherPathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}",
  "catcherUrlPrefix": "",
  "catcherMaxSize": 2048000,
  "catcherAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"],
  "videoActionName": "uploadvideo",
  "videoFieldName": "upfile",
  "videoPathFormat": "/ueditor/jsp/upload/video/{yyyy}{mm}{dd}/{time}{rand:6}",
  "videoUrlPrefix": "",
  "videoMaxSize": 102400000,
  "videoAllowFiles": [
    ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
    ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid"],
  "fileActionName": "uploadfile",
  "fileFieldName": "upfile",
  "filePathFormat": "/ueditor/jsp/upload/file/{yyyy}{mm}{dd}/{time}{rand:6}",
  "fileUrlPrefix": "",
  "fileMaxSize": 51200000,
  "fileAllowFiles": [
    ".png", ".jpg", ".jpeg", ".gif", ".bmp",
    ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
    ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
    ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
    ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
  ],
  "imageManagerActionName": "listimage",
  "imageManagerListPath": "/ueditor/jsp/upload/image/",
  "imageManagerListSize": 20,
  "imageManagerUrlPrefix": "",
  "imageManagerInsertAlign": "none",
  "imageManagerAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"],
  "fileManagerActionName": "listfile",
  "fileManagerListPath": "/ueditor/jsp/upload/file/",
  "fileManagerUrlPrefix": "",
  "fileManagerListSize": 20,
  "fileManagerAllowFiles": [
    ".png", ".jpg", ".jpeg", ".gif", ".bmp",
    ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
    ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
    ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
    ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
  ]
}
View Code

注意: imagePathFormat 的 /ueditor/{time}/{filename} 与下面的UEditorUpload.java 的 returnPath路径保持一直.

 

新建2个类 UEditorFile.java,  UEditorUpload.java 文件

@Data
public class UEditorFile {
    private String state;
    private String url;
    private String title;
    private String original;
}
View Code
package net.hp.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @Description
 * @Date 2022年04月11 11:55:34
 */
@Component
public class UEditorUpload {

    /**
     * 服务器文件ueditor文件存储位置
     */
    @Value("${file.upload.path}")
    private String ueditorPath;

    /**
     * 服务器文件ueditor文件访问位置
     */
    @Value("${file.upload.url}")
    private String ueditorUrl;

    private Logger log = LoggerFactory.getLogger(this.getClass());

    public UEditorFile uploadImage(MultipartFile file) throws IOException {
        log.info("UEditor开始上传文件");
        // 获取文件名
        String fileName = file.getOriginalFilename();
        // Ueditor的config.json规定的返回路径格式一致: "imagePathFormat": "/ueditor/{time}/{filename}",
        String returnPath = "/ueditor/" + System.currentTimeMillis() + "/" + fileName;
        String saveFilePath = ueditorPath + returnPath;
        log.info("UEditor 文件保存地址: " + saveFilePath);
        File saveFile = new File(saveFilePath);
        if (!saveFile.exists()) {
            saveFile.mkdirs();
        }
        // 将临时文件移动到保存路径
        file.transferTo(saveFile);
        log.info("UEditor上传文件成功,保存路径:" + saveFile.getAbsolutePath());
        UEditorFile uEditorFile = new UEditorFile();
        uEditorFile.setState("SUCCESS");
        // 访问URL
        if (StringUtils.hasLength(ueditorUrl)) {
            // 去掉最后一个/
            String laststr = ueditorUrl.substring(ueditorUrl.length() - 1);
            if ("/".equals(laststr)) {
                ueditorUrl = ueditorUrl.substring(0, ueditorUrl.length() - 1);
            }
        }
        String saveFileUrl = ueditorUrl + returnPath;
        uEditorFile.setUrl(saveFileUrl);
        uEditorFile.setTitle(fileName);
        uEditorFile.setOriginal(fileName);
        return uEditorFile;
    }
}
View Code

注意: ueditorPath : 文件存储的路径   ueditorUrl: 文件访问的路径

 

注意文件上传到服务后悔存储在 E:\statices\admin\ueditor\1649649952423\文件名.png

Nginx 静态资源配置.statices.conf, 重启本地Nginx.

server {
    listen       8044;
    location /statices/admin/ueditor/ {
        alias E:/statices/admin/ueditor/;
        index index.html;
    }
}

此时可以通过http://localhost:8044/statices/admin/ueditor/1649649952423/文件名.png  对文件进行访问

 

写我们的控制器:

import com.baidu.ueditor.ActionEnter;
import net.hp.common.utils.UEditorFile;
import net.hp.common.utils.UEditorUpload;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description
 * @Date 2022年04月11 09:29:55
 */
@RestController
@RequestMapping("/ueditor")
public class UeditorController {

    @Autowired
    UEditorUpload ueditorUpload;

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @RequestMapping("/config")
    public String config(HttpServletRequest request, HttpServletResponse response, String action, MultipartFile[] upfile) throws IOException {
        logger.info("UeditorController action:" + action);
        if ("config".equals(action)) {
            logger.info("UeditorController config...");
            request.setCharacterEncoding("utf-8");
            response.setHeader("Content-type", "text/html");
            String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
            logger.info("UeditorController config path:" + path);
            PrintWriter printWriter = response.getWriter();
            String exec = new ActionEnter(request, path).exec();
            logger.info("UeditorController config exec:" + exec);
            printWriter.write(exec);
            printWriter.flush();
            printWriter.close();
        } else if ("uploadimage".equals(action)) {
            logger.info("UeditorController uploadimage...");
            UEditorFile uEditorFile = ueditorUpload.uploadImage(upfile[0]);
            JSONObject jsonObject = new JSONObject(uEditorFile);
            return jsonObject.toString();
        }
        return null;
    }
}
View Code

 

 

 

最后: 前端上传图片时候获取结果成功, 却提示上传失败

 

 

修改ueditor.all.js  ctrl+F 搜索  输入: 

domUtils.on(iframe, 'load' 
找到后,注释3行,并添加后面的代码。

本人参考地址: https://blog.csdn.net/csdn_shenguang/article/details/89026174
                // domUtils.on(iframe, 'load', callback);
                // form.action = utils.formatUrl(imageActionUrl + (imageActionUrl.indexOf('?') == -1 ? '?':'&') + params);
                // form.submit();
                var formdata = new FormData(form);
                var arr,reg=new RegExp("(^| )_token=([^;]*)(;|$)");
                var myForm = document.getElementById("myForm");
                var xhr= new XMLHttpRequest();
                xhr.open("POST", me.getOpt('serverUrl')+'?action=uploadimage', true);
                xhr.onreadystatechange = function() {undefined
                  if (xhr.readyState === 4)
                    if ((xhr.status >=200 && xhr.status < 300) || xhr.status == 304)
                      alert(xhr.responseText);
                }
                xhr.send(formdata);
                xhr.onreadystatechange = function () {undefined
                  if(xhr.readyState == 4) {undefined
                    var response = JSON.parse(xhr.responseText);
                    if(response.state=='SUCCESS' ){undefined
                      loader = me.document.getElementById(loadingId);
                      // loader.setAttribute('src', me.getOpt('serverUrl')+response.url);
                      // loader.setAttribute('_src', me.getOpt('serverUrl')+response.url);
                      // loader.setAttribute('src', me.options.imageUrlPrefix+response.url);
                      // loader.setAttribute('_src', me.options.imageUrlPrefix+response.url);
                      loader.setAttribute('src', response.url);
                      loader.setAttribute('_src', response.url);
                      loader.setAttribute('title', response.title || '');
                      loader.setAttribute('alt', response.original || '');
                      loader.removeAttribute('id');
                      domUtils.removeClasses(loader, 'loadingclass');
                    }
                  }
                }

此时大公告成,谢谢各位.

 

posted on 2022-04-11 16:33  1161588342  阅读(505)  评论(0编辑  收藏  举报