SpringBoot integration with UEditor notes

Because the project needs to change the rich text editor, I found several open source functions are too simple. In addition, I found that the indentation effect of paragraphs and first lines in the original rich text editor is not good, and the indentation effect cannot be displayed in the front page.

So I decided to change the rich text editor. After searching, I finally chose UEditor, where I simply recorded the pits I stepped on.

Ueditor official website: ueditor.baidu.com

Ueditor API documentation: ueditor.baidu.com/doc

Ueditor Github address: github.com/fex-team/ue…

I directly use the compression package sent to me by my colleague here, but I can’t see what version it is.

If you don’t mind version, compressed package takes: link: pan.baidu.com/s/1LYMpDjC9… Extraction code: AFIX

Unzip it and put it directly into the static/js folder of your project:

One thing to note here is that since only the JS of the Ueditor is imported when the page is referenced, the CSS to be used in it may be imported automatically, so you need to ensure that static resources cannot be intercepted by the back end.

The first is to complete the page first, directly copy the index. HTML inside the compressed package directly to our own page can also be complete. The page should display fine at this point.

At this time can be tested, access to the contents of the edit box, what is basically normal, but the picture insert this most basic function, there is a problem.

Open the console, you can see such an exception: background configuration item return format error, upload function will not be normal use!

This is annoying…

Then AFTER searching, I found that none of them could solve my problem smoothly.

Since Springboot was used, I found that the official document stopped for too long, resulting in JSP related problems after the demo, which could not solve my problem.

It mentioned the need to introduce several basic JAR packages, which I have checked and included in the current project. If not, I suggest to add them to avoid problems that should not occur.

These basic JAR packages should be available in the project. The version I use here is newer than this one, so there should be no problem with the version.

After I solved the rich text editor, I thought about it. The main problem is that the rich text editor has a default interface for uploading pictures (files), and the configuration file for uploading files is not in a traditional JS, it goes in the mode of front and back interaction.

If you use a JSP as a page, you need to configure an interface that returns a JSP \controller.jsp page.

Visible in ueditor.config.js

This interface should return a JSON string containing the contents of config.json in the JSP folder of the zip package. This interface is automatically called after the page has finished loading.

In addition, this interface also needs to be released by the back end, which cannot be intercepted. Since SHIRo is used as the authentication on the back end, it is directly released by the configuration here. There is no way to add a token parameter to this interface.

The backing interface code is as follows:


/** * This file interface is used for Ueditor, currently only for image upload function * interface name is fixed * interface return information is fixed *@Auther linmengmeng
 * @Date The 2021-08-03 14:55 * /
@Slf4j
@RestController
@RequestMapping("/ueditor")
@Module("ueditor")
@Api(value = Ueditor Rich text Editor API, tags = {Ueditor Rich text editor})
public class UeditorController {

    @Autowired
    private UploadFileService uploadFileService;

    /** * Upload configuration: that is, do not go to config.json and simulate the content in config.json to solve the problem that the backend configuration items are incorrect and cannot be uploaded. * If you need to configure other files to be uploaded, directly add the content in config.json to the returned parameters@return* /
    @RequestMapping("/config")
    public Map<String.Object> uploadConfig() {
        Map<String.Object> map = new HashMap<>();
        List<String> imageAllowFilesList = new ArrayList<>();
        imageAllowFilesList.add(".png");
        imageAllowFilesList.add(".jpg");
        imageAllowFilesList.add(".jpeg");
        imageAllowFilesList.add(".gif");
        imageAllowFilesList.add(".bmp");
        map.put("imageActionName"."uploadimage");
        map.put("imageFieldName"."file");
        map.put("imageMaxSize".2048000);
        map.put("imageAllowFiles", imageAllowFilesList);
        map.put("imageCompressEnable".true);
        map.put("imageInsertAlign".1600);
        map.put("imageCompressBorder"."none");
        map.put("imageUrlPrefix"."");
        map.put("imagePathFormat"."/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}");
        return map;
    }


    @PostMapping("/upload")
    public Map<String.String> uploadFile(MultipartFile file) throws Exception {
        log.info("name:{}", file.getName());
        log.info("size:{}", file.getSize());
        log.info("getOriginalFilename:{}", file.getOriginalFilename());
        UploadFileParam uploadFileParam = new UploadFileParam();
        uploadFileParam.setUploadType(ConstEnum.UploadFileFolderEnum.COMMON_EDITOR.getFileType());
        String uploadPath = uploadFileService.saveUploadFile(file, uploadFileParam, true);

        String newFilename = uploadPath.substring(uploadPath.lastIndexOf("/"));

        Map<String.String> map = new HashMap<>();
        map.put("state"."SUCCESS");
        map.put("url", uploadPath);
        map.put("title", newFilename);
        map.put("original", newFilename);

        returnmap; }}Copy the code

This interface is automatically invoked when the current page is displayed. The following information is displayed:

This solves the first problem, and there should be no exception messages on the console.

But the new problem came out again, upload the picture failed, there is only a circle in the rich text box, the picture echo can not, the background can not accept the request of the picture upload interface.

This will need to add a custom upload image configuration in the page.


// Instantiate the editor
// It is recommended to use the factory method getEditor to create and reference an editor instance. If you reference the editor in a closure, call ue.geteditor ('editor') directly to get the related instance
var ue = UE.getEditor('editor');

ue.ready(function () {
    // ue.setContent(''); // Set the rich text editor to initialize data
    ue.execCommand('serverparam'.function(editor) {
        return {
            'token': token // Sets the extra parameters to be carried when the rich text editor requests it
        };
    });
});

// Customize Ueditor image uploads
UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;

UE.Editor.prototype.getActionUrl = function(action) {
    console.log("action", action);
    if (action == 'uploadimage') {console.log("---------uploadimage--------");
        return '/ueditor/upload'; /* Upload your own pictures to action */
    }else{
        return this._bkGetActionUrl.call(this, action); }};Copy the code

Add the above code, you can upload the image will normally go to our background interface, here is the Ueditor support custom image upload interface configuration.

There are a couple of things to note here.

Action == ‘uploadimage’. This uploadimage corresponds to the imageActionName value returned by the config interface.

Second: if the backend has authentication mechanism, it also needs to carry additional parameters, such as token, which is configured for interface interaction after the rich text editor is successfully loaded.

Third: image echo problem.

This is dependent on our upload image interface, upload image interface return JSON content has special requirements. The above interface is my self-defined public file upload interface. It has little to do with the rich text editor, as long as the image is actually transmitted to our back end normally, and the JSON content returned by the interface is consistent.

The value of “state” must be “SUCCESS”; otherwise, the upload fails to be recognized.

The URL is the complete echo address of the picture, which can be tested separately. The echo address must be normally accessible in our browser, otherwise the picture cannot be displayed.

The other two arguments, title and original, are used in HTML tags.

Take a look at the effect:

Then use the rich text editor’s own view HTML source function, look at the source:

<p style="text-indent: 2em;">
    <span style="The font-family: song typeface. font-size: x-large; font-weight: bold;"></span>
</p>
<p>
    <span style="font-size: x-large; text-indent: 24pt; line-height: 150%; The font-family: imitation song dynasty style typeface;"><img src="http://127.0.0.1:8088//resource/common_editor\202108031921230291548.gif" title="/common_editor\202108031921230291548.gif" alt="/common_editor\202108031921230291548.gif"/></span>
</p>
<p>
    <br/>
</p>
Copy the code

At this point, even if the rich text editor image upload, small problem, torturing for most of the day……

Think of the joke of a child on Douyin yesterday: if I get good grades, I am the best in the world, and if I get bad grades, I am a sloppy thing

When the problem is solved, I am a small problem. When the problem is not solved, I feel like nothing.

Reference blog: blog.csdn.net/qq_36737803…