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

11,434次阅读
没有评论

共计 5856 个字符,预计需要花费 15 分钟才能阅读完成。

一:引入 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}" />


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 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();
				
				$('#ueedit').html(html);
			}
		}

		
		editorConfig.MENU_CONF['uploadImage'] = {
			server: ctxPath+'/api/business/wangeditor/upload',
			fieldName: 'file',
			maxFileSize: 2 * 1024 * 1024, 
			
			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', 
					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) {   
				
				console.log(res);
				
				
			},
		}


		editorConfig.MENU_CONF['uploadVideo'] = {
			
			fieldName: 'file',
			
			maxFileSize: 5 * 1024 * 1024, 
			
			maxNumberOfFiles: 3,
			
			allowedFileTypes: ['video/*'],
			
			meta: sys_qm({
			}),
			headers: {
				'X-Token':Data.windowGet("User-Token"),
			},
			
			metaWithUrl: false,
			
			
			withCredentials: true,
			
			timeout: 15 * 1000, 
			
			
			async customUpload(file, insertFn) {
				let formData = new FormData();
				formData.append('file', file);
				$.ajax({
					url: ctxPath+'/api/business/wangeditor/upload', 
					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', 
		})

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

	}
	
	function init(){
		var 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 ApiResultObject> 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();
                }
            }

            
            ftpUtil.upload("wangEditor", fileName, fileSave);
            MapString,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) {
        
        String bmpPath = "D:images";
        registry.addResourceHandler("/images/**").addResourceLocations("file:"+bmpPath );
    }




}

五:实现截图

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

六:总结

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

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

    正文完
     0
    Yojack
    版权声明:本篇文章由 Yojack 于2024-10-03发表,共计5856字。
    转载说明:
    1 本网站名称:优杰开发笔记
    2 本站永久网址:https://yojack.cn
    3 本网站的文章部分内容可能来源于网络,仅供大家学习与参考,如有侵权,请联系站长进行删除处理。
    4 本站一切资源不代表本站立场,并不代表本站赞同其观点和对其真实性负责。
    5 本站所有内容均可转载及分享, 但请注明出处
    6 我们始终尊重原创作者的版权,所有文章在发布时,均尽可能注明出处与作者。
    7 站长邮箱:laylwenl@gmail.com
    评论(没有评论)