KindEditor-Rich text editor supporting word upload

After 1.4.2, the official has not made any functional changes. 1.4.2 There is no bug in the word copy section, and other versions will not be able to transfer manually.

The backend used in this article is Java. The front end is Jsp (the front end is the same, if the background language is not good, you have to do Base64 encoding and decoding by yourself)

Because the company's business needs to support IE8, there are actually many rich text boxes on the Internet, and the effect is very good.

For example, www.wangEditor.com did not support IE8 after a trial.

So back to Ueditor, due to the official lack of maintenance, the new neuditor does not know when it will support word automatic dumping, so I can only figure out a solution by myself.

If it is not necessary, ueditor is not recommended. I have no alternative.

The modified plug-in is only suitable for IE8.

The point to be explained here is that Baidu's official editor does not support word image batch dumping. After pasting the word, you need to manually select the image and upload it again. Most of the examples found on the Internet are for this operation. If you need to upload word images in batches automatically, you can use the WordPaster control.

 

1. IE settings

Add trusted sites to trusted sites.

The local test here is directly http://localhost

Because you need to read the client's file, you need to set up permission to access the data source.

ActiveXObject settings can go to the Internet for reference, not listed here.

front

The preparations for IE are now complete.

Modify the key code of ueditor.all.js

Near line 14006, if it is another version of ueditor, if the function is normal, you can copy the following code.

var imgPath = attrs.src;

var imgUrl = attrs.src;

if (navigator.appName ==='Microsoft Internet Explorer') {// Determine whether it is IE browser

    if (navigator.userAgent.match(/Trident/i) && navigator.userAgent.match(/MSIE 8.0/i)) {//Determine whether the browser kernel is Trident kernel IE8.0

        var realPath = imgPath.substring(8, imgPath.length);

        var filename = imgPath.substring(imgPath.lastIndexOf('/') + 1, imgPath.length);

        var result = UploadForIE.saveAttachment(filename, realPath);

        if (result) {

            var json = eval('(' + result + ')');

            imgUrl = json.url;

        }

    }

}

img.setAttr({

 

    width: attrs.width,

    height: attrs.height,

    alt: attrs.alt,

    word_img: attrs.src,

    src: imgUrl,

    'style': 'background:url(' + (flag ? opt.themePath + opt.theme + '/images/word.gif': opt.langPath + opt.lang + '/images/localimage.png') + ') no-repeat center center;border:1px solid #ddd'

})

 

uploadForIE.js。

var UploadForIE = {

    // Save to xml attachment and upload via ajax

    saveAttachment: function(upload_filename, localFilePath) {

        //The method of accepting picture saving in the background.

        var upload_target_url = "uploadImg";

        var strTempFile = localFilePath;

        // Create an XML object and combine XML document data

        var xml_dom = UploadForIE.createDocument ();

        xml_dom.loadXML('<?xml version="1.0" encoding="GBK" ?> <root/>');

        // Create ADODB.Stream object

        var ado_stream = new ActiveXObject("adodb.stream");

        // Set the stream data type to binary type

        ado_stream.Type = 1; // adTypeBinary

        // Open the ADODB.Stream object

        ado_stream.Open();

        // Load the local file into the ADODB.Stream object

        ado_stream.LoadFromFile(strTempFile);

        // Get the file size (in bytes)

        var byte_size = ado_stream.Size;

        // Set the data transmission unit size to 1KB

        var byte_unit = 1024;

        // Get the number of file split data units

        var read_count = parseInt((byte_size / byte_unit).toString()) + parseInt(((byte_size % byte_unit) == 0) ? 0 : 1);

 

        // Create an XML element node and save the uploaded file name

        var node = xml_dom.createElement("uploadFilename");

        node.text = upload_filename.toString();

        var root = xml_dom.documentElement;

        root.appendChild(node);

 

        // Create an XML element node and save the uploaded file size

        var node = xml_dom.createElement("uploadFileSize");

        node.text = byte_size.toString();

        root.appendChild(node);

 

        // Create an XML element node and save the uploaded file content

        for (var i = 0; i < read_count; i++) {

            var node = xml_dom.createElement("uploadContent");

            // The file content encoding method is Base64

            node.dataType = "bin.base64";

            // Determine the size of the currently saved data node and perform classification operations according to conditions

            if ((parseInt(byte_size % byte_unit) != 0) && (i == parseInt(read_count - 1))) {

                // When the data packet size is not an integral multiple of the data unit, read the last remaining data that is smaller than the data unit

                node.nodeTypedValue = ado_stream.Read();

            } else {

                // Read the data of a complete data unit

                node.nodeTypedValue = ado_stream.Read(byte_unit);

            }

            root.appendChild(node);

        }

 

        // Close the ADODB.Stream object

        ado_stream.Close();

        delete ado_stream;

        // Create Microsoft.XMLHTTP object

        // var xmlhttp = new ActiveXObject("microsoft.xmlhttp");

        var xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHttp");

        // Open the Microsoft.XMLHTP object

        xmlhttp.open("post", upload_target_url, false);

        // Upload files using Microsoft.XMLHTP object

        xmlhttp.send(xml_dom);

        var state = xmlhttp.readyState;

        var success_state = true;

        if (state != 4) {

            success_state = false;

        }

        var result = xmlhttp.responseText;

 

        delete xmlhttp;

        return result;

    },

 

    // Create DOMdocuemnt

    createDocument: function() {

        var xmldom;

        var versions = ["MSXML2.DOMDocument.6.0", "MSXML2.DOMDocument.5.0", "MSXML2.DOMDocument.4.0", "MSXML2.DOMDocument.3.0", "MSXML2.DOMDocument"],

        i,

        len;

        for (i = 0, len = versions.length; i < len; i++) {

            try {

                xmldom = new ActiveXObject(versions[i]);

                if (xmldom != null) break;

            } catch(ex) {

                //jump over

                alert("Failed to create document object!");

            }

        }

        return xmldom;

    }

}

 

UEditorAction save picture method

@RequestMapping("/uploadImg")

    public void uploadADO(HttpServletRequest request, HttpServletResponse response) {

        String path1 = request.getContextPath();

        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() +path1;

 

        String rootPath = request.getServletContext().getRealPath("/");

        // Set the data transmission unit size to 1KB

        int unit_size = 1024;

        // Initialize the xml file size (in bytes)

        int xmlFileSize = 0;

        // Initialize upload file name (full file name)

        String xmlFilename = "";

        // Initialize upload file save path (absolute physical path)

        String xmlFilepath = "";

        // Declare file storage byte array

        byte[] xmlFileBytes = null;

        try {

            // Initialize the SAX serial xml file parser

            SAXBuilder builder = new SAXBuilder();

            Document doc = builder.build(request.getInputStream());

            Element eRoot = doc.getRootElement ();

            // Get the full name of the uploaded file

            Iterator it_name = eRoot.getChildren("uploadFilename").iterator();

            if (it_name.hasNext()) {

                xmlFilename = ((Element) it_name.next()).getText();

            }

            //The relative path directory stored

            String  relativePath = "/temp/"+EditorUtil.getToday()+"/";

            xmlFilepath = rootPath+ relativePath;

 

            // Get the size of the uploaded file

            Iterator it_size = eRoot.getChildren("uploadFileSize").iterator();

            if (it_size.hasNext()) {

                xmlFileSize = Integer.parseInt(((Element) it_size.next())

                        .getText());

                if (xmlFileSize > 0) {

                    int unit_count = 0;

                    // Allocate storage space for the byte array storing the contents of the file

                    xmlFileBytes = new byte[xmlFileSize];

                    // Read the contents of the file in a loop and save it to the byte array

                    Iterator it_content = eRoot.getChildren("uploadContent")

                            .iterator();

                    while (it_content.hasNext()) {

                        // Initialize the Base64 codec

                        BASE64Decoder base64 = new BASE64Decoder();

                        byte[] xmlNodeByteArray = base64

                                .decodeBuffer(((Element) it_content.next())

                                        .getText());

                        if (xmlNodeByteArray.length >= unit_size) {

                            // Read the data of a complete data unit

                            System.arraycopy(xmlNodeByteArray, 0, xmlFileBytes,

                                    unit_count * unit_size, unit_size);

                        } else {

                            // Read all data less than one data unit

                            System.arraycopy(xmlNodeByteArray, 0, xmlFileBytes,

                                    unit_count * unit_size, xmlFileSize

                                            % unit_size);

                        }

                        // Continue to read the contents of the file downward

                        unit_count++;

                    }

                }

            }

 

            // save route

            File path = new File(xmlFilepath);

            if(!path.exists()){

                path.mkdirs();

            }

            // Save the file word and paste the name of the picture

            File file = new File(path,xmlFilename);

            // Create file input and output stream

            FileOutputStream fos = new FileOutputStream(file);

            // write file content

            fos.write(xmlFileBytes);

            fos.flush();

            // Close the file input and output stream

            fos.close();

 

            ReturnUploadImage rui = new ReturnUploadImage();

            rui.setTitle(xmlFilename);//The file name needs to be set here, such as: xxx.jpg

            rui.setOriginal(xmlFilename);//The file name needs to be set here, such as: xxx.jpg

            rui.setState("SUCCESS");

            rui.setUrl(basePath +relativePath+xmlFilename);

 

            JSONObject json = new JSONObject(rui);

            String result = json.toString();//This is the format conversion for returning to UEditor

            response.getWriter().write(result);

        } catch (Exception e) {

            e.printStackTrace ();

        }

    }

Optimized code:

upload.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>

<%@ page contentType="text/html;charset=utf-8"%>

<%@ page import = "Xproer.*" %>

<%@ page import="org.apache.commons.lang.StringUtils" %>

<%@ page import="org.apache.commons.fileupload.*" %>

<%@ page import="org.apache.commons.fileupload.disk.*" %>

<%@ page import="org.apache.commons.fileupload.servlet.*" %>

<%out.clear();

/* 

    update record:

        2013-01-25 Cancel the use of SmartUpload and use the commons-fileupload component instead. Because the test found that SmartUpload has a memory leak.

*/

//String path = request.getContextPath();

//String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

 

String uname = "";//        = request.getParameter("uid");

String upass = "";//        = request.getParameter("fid");

 

// Check that we have a file upload request

boolean isMultipart = ServletFileUpload.isMultipartContent(request);

FileItemFactory factory = new DiskFileItemFactory();  

ServletFileUpload upload = new ServletFileUpload(factory);

//upload.setSizeMax(262144);//256KB

List files = null;

try

{

    files = upload.parseRequest(request);

}

catch (FileUploadException e)

{// Handling file size exception 

    out.println("Upload file exception:"+e.toString());

    return;

  

}

 

FileItem imgFile = null;

// Get all uploaded files

Iterator fileItr = files.iterator();

// Loop through all files

while (fileItr.hasNext())

{

    // Get the current file

    imgFile = (FileItem) fileItr.next();

    // Ignore the simple form field instead of the file field of the upload field (<input type="text" /> etc.)

    if(imgFile.isFormField())

    {

        String fn = imgFile.getFieldName();

        String fv = imgFile.getString();

        if(fn.equals("uname")) uname = fv;

        if(fn.equals("upass")) upass = fv;

    }

    else

    {

        break;

    }

}

Uploader up = new Uploader(pageContext,request);

up.SaveFile(imgFile);

String url = up.GetFilePathRel();

out.write(url);

response.setHeader("Content-Length",url.length()+"");//Return the Content-length tag so that the control can read the return address correctly.

%>

 

For the remaining background functions and js, refer to UEditorAction and uploadForIE.js in the download file.

The following is the dependent pom structure I installed, which can be adjusted according to my own.

  <dependency>

            <groupId>com.baidu</groupId>

            <artifactId>ueditor</artifactId>

            <version>1.1.0</version>

        </dependency>

 

Based on springboot and idea, only the automatic dump function has been extracted here. The function has not been tested yet, and the git code has not been made public, and will be made public after subsequent testing.

You can use csdn to download and view the code first.

ueditor.jar is referenced in pom

You need to install the jar package according to your situation

The jar package version in 1.4.2 is 1.1.0

mvn install:install-file -DgroupId=com.baidu -DartifactId=ueditor -Dversion=1.1.0 -Dpackaging=jar -Dfile=\ueditor\jsp\lib\ueditor-1.1.0.jar

run

Main method of UeditorApplication

Then visit http://localhost:8088/ueditor/ to test.

 

The effect after completion:

Pictures are uploaded in batches automatically, no need to manually select pictures to upload one by one, the user experience is better than that of Baidu ueditor, and the uploading efficiency is higher.

 

After the upload is successful, the image address is automatically replaced with the server address

 

The picture is automatically saved in the server

 

For details, please refer to this article:

http://blog.ncmem.com/wordpress/2019/08/12/ueditor-word%E5%9B%BE%E7%89%87%E8%BD%AC%E5%AD%98%E4%BA%A4%E4%BA%92/

 

Discussion group: 223813913

Guess you like

Origin blog.csdn.net/weixin_45525177/article/details/108658403