word paste picture to ckeitor

Posted by TheBentinel.com on Fri, 04 Mar 2022 19:44:19 +0100

After 1.4.2, the official did not make functional changes. There was no bug in word copy in 1.4.2, and other versions could not be transferred manually

The background 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, with good results.

for example www.wangEditor.com But I didn't support IE8 after trying for a lap.

So back to Ueditor, because there is no official maintenance, the new neuditor doesn't know when it can support word automatic transfer, so we can only find a way by ourselves.

If not necessary, ueditor is not recommended. I can't help it.

The changed plug-in is only suitable for IE8.

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

1.IE settings

Add trusted sites to trusted sites.

The direct test used here is localhost

Because you need to read the files of the client, you need to set the permission to access the data source.

ActiveXObject settings can be referred to online. They are not listed here.

ahead

Here, IE's preparation is completed.

Modify ueditor all. JS key code

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

var imgPath = attrs.src;

var imgUrl = attrs.src;

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

if (navigator.userAgent.match(/Trident/i) && navigator.userAgent.match(/MSIE 8.0/i)) { //Judge 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 background accepts the method of image saving.

    var upload_target_url = "uploadImg";

    var strTempFile = localFilePath;

    // Create XML objects 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

    ado_stream.Type = 1; // adTypeBinary

    // Open ADODB Stream object

    ado_stream.Open();

    // Load local files into ADODB In stream object

    ado_stream.LoadFromFile(strTempFile);

    // Gets the file size in bytes

    var byte_size = ado_stream.Size;

    // Set the data transmission unit size to 1KB

    var byte_unit = 1024;

    // Gets 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 name of the uploaded file

    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 encoding method of file content is Base64

        node.dataType = "bin.base64";

        // Judge the size of the currently saved data node and classify it according to the conditions

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

            // When the packet size is not an integer multiple of the data unit, read all the remaining data less 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 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 Microsoft Xmlhtp object

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

    // Use Microsoft Xmlhtp object upload file

    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) {

            //skip

            alert("establish document Object failed!");

        }

    }

    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 xml file size in bytes

    int xmlFileSize = 0;

    // Initialization upload file name (full file name)

    String xmlFilename = "";

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

    String xmlFilepath = "";

    // Declaration file storage byte array

    byte[] xmlFileBytes = null;

    try {

        // Initialize 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();

        }

        //Relative path directory of storage

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

        xmlFilepath = rootPath+ relativePath;

        // Gets 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 that stores the contents of the file

                xmlFileBytes = new byte[xmlFileSize];

                // Loop to read the contents of the file and save it to the byte array

                Iterator it_content = eRoot.getChildren("uploadContent")

                        .iterator();

                while (it_content.hasNext()) {

                    // Initialize 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 down the contents of the file

                    unit_count++;

                }

            }

        }

        // Save path

        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 / output stream

        FileOutputStream fos = new FileOutputStream(file);

        // Write file contents

        fos.write(xmlFileBytes);

        fos.flush();

        // Close file input / output stream

        fos.close();

        ReturnUploadImage rui = new ReturnUploadImage();

        rui.setTitle(xmlFilename);//You need to set the file name here, such as XXX jpg

        rui.setOriginal(xmlFilename);//You need to set the file name here, such as XXX jpg

        rui.setState("SUCCESS");

        rui.setUrl(basePath +relativePath+xmlFilename);

        JSONObject json = new JSONObject(rui);

        String result = json.toString();//This is to return the format conversion 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 pair SmartUpload Use of, use instead commons-fileupload Components. Because the test found SmartUpload There is 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)

{/ / handle the exception that the file size is too large

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

return;

}

FileItem imgFile = null;

//Get all uploaded files

Iterator fileItr = files.iterator();

//Cycle through all files

while (fileItr.hasNext())

{

// Get 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 correctly read the return address.

%>

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

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

        <groupId>com.baidu</groupId>

        <artifactId>ueditor</artifactId>

        <version>1.1.0</version>

    </dependency>

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

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

Ueditor is quoted in pom jar

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

function

main method of UeditorApplication

Then visit localhost:8088/ueditor/ You can test it.

Effect after completion:

Images are uploaded automatically in batches. There is no need to manually select images to upload one by one. The user experience is better and the image transmission efficiency is higher than that of Baidu ueditor.

After uploading successfully, the picture address will be automatically replaced with the server address

Pictures are automatically saved in the server

For details, please refer to this article:

blog.ncmem.com/wordpress/2019/08/12...

Discussion group: 223813913

Topics: Vue.js