SpringBoot,前端html5 整合WangEditor5富文本编辑器,并自定义图片、视频上传至FTP服务器

一:引入css以及js

WangEditor5 官网 https://www.wangeditor.com/

<!-- 引入 css -->
<link href="https://unpkg.com/@wangeditor/editor@latest/dist/css/style.css" rel="stylesheet">
<!-- 引入 js -->
<script src="https://unpkg.com/@wangeditor/editor@latest/dist/index.js"></script>

推荐下载到本地引入,有时候发现CDN 访问不成功。

二:H5前端整合编辑器

这里遇到的坑:原生的图片和视频上传,不懂为什么配置多个上传参数无效(即maxNumberOfFiles参数),配置成多个后台也只能接收到一个,返回参数即使按照官网所需,上传第二个的时候js就报错了。所以这里直接用自定义方法上传了,后台只需返回图片或视频URL即可。
有发现并解决这个问题的伙伴麻烦解答一下~

<!DOCTYPE html>
<html lang="zh-cn" xmlns:th="http://www.thymeleaf.org">
<head th:include="template/head_template::commonHead">
</head>
<link rel="stylesheet" th:href="@{/js/Wangeditor/style.css}" />
<!--<link href="https://unpkg.com/@wangeditor/editor@latest/dist/css/style.css" rel="stylesheet">-->

<style>
	.dropdown-menu{
		min-width: 240px;
	}

	#editor—wrapper {
		border: 1px solid #ccc;
		z-index: 100; /* 按需定义 */
	}
	#toolbar-container { border-bottom: 1px solid #ccc; }
	#editor-container { min-height: 450px; }
</style>

<body>

	<form id="wd_main_InfoTable" action=""  style="overflow-x:hidden;"  >   
		<textarea  id="ueedit" name="ueedit" hidden ></textarea>
		<div id="editor—wrapper"    >
				<div id="toolbar-container"><!-- 工具栏 --></div>
				<div id="editor-container"><!-- 编辑器 --></div>
		</div>
	</form>

<!--<script src="https://unpkg.com/@wangeditor/editor@latest/dist/index.js"></script>-->
<script th:src="@{/js/Wangeditor/index.js}"></script>
	
	<script>
	var ctxPath=Data.windowGet("ctxPath");
	var editor ;
	function init_editor(editor_html) {
		//配置项
		const {createEditor, createToolbar} = window.wangEditor
		const editorConfig = {
			MENU_CONF: {},
			placeholder: '请编写...',
			onChange(editor) {
				const html = editor.getHtml();
				//const html = editor.getHtml();
				$('#ueedit').html(html);
			}
		}

		//上传图片
		editorConfig.MENU_CONF['uploadImage'] = {
			server: ctxPath+'/api/business/wangeditor/upload',
			fieldName: 'file',
			maxFileSize: 2 * 1024 * 1024, // 1M
			// 最多可上传几个文件,默认为 100
			maxNumberOfFiles: 5,
			allowedFileTypes: ['image/*'],
			meta: sys_qm({
			}),
			headers: {
				'X-Token':Data.windowGet("User-Token"),
			},
			// 单个文件上传失败
			onFailed(file, res) {
				console.log('上传失败', res)
			},
			//重写上传图片方法
			async customUpload(file, insertFn) {
				let formData = new FormData();
				formData.append('file', file);
				$.ajax({
					url: ctxPath+'/api/business/wangeditor/upload', //设置后台接收图片的URL地址
					type: 'POST',
					dataType: 'json',
					data: formData,
					processData: false,
					contentType: false,
					success: function (res) {
						console.log(res);
						if(res.code=='200'){
							insertFn(res.data.url, "", "");
						}
					},
					error: function () {
						console.error('上传失败');
					}
				});
			},
			customInsert(res, insertFn) {   // JS 语法
				// res 即服务端的返回结果
				console.log(res);
				// 从 res 中找到 url alt href ,然后插入图片
				//insertFn(url, alt, href)
			},
		}


		editorConfig.MENU_CONF['uploadVideo'] = {
			// form-data fieldName ,默认值 'wangeditor-uploaded-video'
			fieldName: 'file',
			// 单个文件的最大体积限制,默认为 10M
			maxFileSize: 5 * 1024 * 1024, // 5M
			// 最多可上传几个文件,默认为 5
			maxNumberOfFiles: 3,
			// 选择文件时的类型限制,默认为 ['video/*'] 。如不想限制,则设置为 []
			allowedFileTypes: ['video/*'],
			// 自定义上传参数,例如传递验证的 token 等。参数会被添加到 formData 中,一起上传到服务端。
			meta: sys_qm({
			}),
			headers: {
				'X-Token':Data.windowGet("User-Token"),
			},
			// 将 meta 拼接到 url 参数中,默认 false
			metaWithUrl: false,
			// 自定义增加 http  header
			// 跨域是否传递 cookie ,默认为 false
			withCredentials: true,
			// 超时时间,默认为 30 秒
			timeout: 15 * 1000, // 15 秒
			// 视频不支持 base64 格式插入
			//重写上传视频方法
			async customUpload(file, insertFn) {
				let formData = new FormData();
				formData.append('file', file);
				$.ajax({
					url: ctxPath+'/api/business/wangeditor/upload', //设置后台接收视频的URL地址
					type: 'POST',
					dataType: 'json',
					data: formData,
					processData: false,
					contentType: false,
					success: function (res) {
						if(res.code=='200'){
							insertFn(res.data.url, "")
						}
					},
					error: function () {
						console.error('上传失败');
					}
				});
			},
		}

		editor = createEditor({
			selector: '#editor-container',
			html: editor_html,//预置内容
			config: editorConfig,
			mode: 'default', // or 'simple'
		})

		const toolbarConfig = {}
		const toolbar = createToolbar({
			editor,
			selector: '#toolbar-container',
			config: toolbarConfig,
			uploadVideoShow: false,
			mode: 'default', // or 'simple'
		})

	}
	
	function init(){
		var html = ``;
		//这里可以取数据库存的html直接生成预置内容
		init_editor(html);
	}
	
	init();

	</script>
</body>
</html>

三:后台接收并保存文件至本地以及FTP

我这里是因为工作的需求文件才放到FTP,没必要的直接存本地即可。

package com.txy.modules.business.Wangeditor;


import com.txy.modules.common.dto.output.ApiResult;
import com.txy.modules.common.entity.Attachment;
import com.txy.utils.ftp.FtpUtil;
import com.txy.utils.spring.SpringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.logging.log4j.util.PropertiesUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.configurationprocessor.json.JSONArray;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("api/business/wangeditor")
@Api(value = "wangeditor后台配置")
public class WangEditorController {


    private String basicLocation = "D:\\images\\";

    @Autowired
    private FtpUtil ftpUtil;


    @ResponseBody
    @PostMapping("/upload")
    @ApiOperation("上传图片")
    public ApiResult<Object> save_main(HttpServletRequest request, HttpServletResponse response,
                                       @RequestPart("file") MultipartFile file, @ApiParam("com.zhoukai.modules.common.dto.input.validate.CommonParamsInput")String params) throws IOException, JSONException {

            String suffix = "";
            String originalFilename = file.getOriginalFilename();
            String uuid = UUID.randomUUID().toString();
            if (originalFilename.contains(".")) {
                suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            String fileName=uuid+suffix;
            File fileSave = new File(basicLocation ,fileName);
            if (!fileSave.getParentFile().exists()) {
                fileSave.getParentFile().mkdirs();
            }
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(fileSave);
                fos.write(file.getBytes());

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            //接着上传到FTP文件服务器上面 这里用了Hutool工具库 实现方法就不粘贴出来了
            ftpUtil.upload("wangEditor", fileName, fileSave);
            Map<String,Object> map = new HashMap();
            map.put("status",0);
            map.put("url","http://192.168.0.219:2233/wangEditor/"+fileName);

            return ApiResult.success(map);
    }





}

四:配置文件,通过url访问本地的图片

package com.zhoukai.modules.business.editor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Component
public class PhotoUtils  implements WebMvcConfigurer {


    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        /**
         * 访问路径:http://localhost:2233/images/test.jpg
         * "/image/**" 为前端URL访问路径
         * "file:" + bmpPath 是本地磁盘映射
         */
        String bmpPath = "D:\\images\\";
        registry.addResourceHandler("/images/**").addResourceLocations("file:"+bmpPath );
    }




}

五:实现截图

在这里插入图片描述

六:总结

WangEditor 自带的文件上传(官网支持多个上传)功能未实现~~,报错在于index.js中,没深究其原因,希望实现的大佬刷到此文章踢我一脚

  • 16
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值