當前位置:首頁 > IT技術(shù) > Web編程 > 正文

如何復(fù)制word的圖文到KindEditor中自動上傳
2021-10-20 10:37:25

?

1.4.2之后官方并沒有做功能的改動,1.4.2在word復(fù)制這塊沒有bug,其他版本會出現(xiàn)手動無法轉(zhuǎn)存的情況

本文使用的后臺是Java。前端為Jsp(前端都一樣,后臺如果語言不通得自己做 Base64編碼解碼)

因為公司業(yè)務(wù)需要支持IE8 ,網(wǎng)上其實有很多富文本框,效果都很好。

例如www.wangEditor.com? 但試了一圈都不支持IE8 。

所以回到Ueditor,由于官方?jīng)]有維護,新的neuditor 也不知道什么時候能支持word自動轉(zhuǎn)存,只能自己想辦法。

如果沒有必要,不建議使用ueditor。我也是沒有辦法。

改動過后的插件只適合IE8。

這里要說明的一點是百度官方的編輯器不支持word圖片批量轉(zhuǎn)存,粘貼word后需要手動選擇圖片再進行上傳一次操作。網(wǎng)上找到的大部分的示例都是這個操作。如果需要自動批量上傳word圖片的話可以使用WordPaster這個控件。

?

1.IE設(shè)置

在受信任站點里添加信任網(wǎng)站。

這里本機測試使用的直接是?? http://localhost

因為需要讀取客戶端的文件,所以需要設(shè)置允許訪問數(shù)據(jù)源。

ActiveXObject設(shè)置可以去網(wǎng)上參考,這里不列舉了。

前面的

到這里 IE 的準備工作完成了。

修改ueditor.all.js關(guān)鍵代碼

14006行附近,如果是其他版本的ueditor,在功能正常的情況下,可以拷貝下面代碼。

var imgPath?= attrs.src;

var imgUrl?= attrs.src;

if?(navigator.appName?===?'Microsoft Internet Explorer')?{?//判斷是否是IE瀏覽器

????if?(navigator.userAgent.match(/Trident/i)?&& navigator.userAgent.match(/MSIE 8.0/i))?{?//判斷瀏覽器內(nèi)核是否為Trident內(nèi)核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?=?{

????//?保存到xml附件,并且通過ajax 上傳

??? saveAttachment:?function(upload_filename,?localFilePath)?{

????????//后臺接受圖片保存的方法。

??????? var upload_target_url?=?"uploadImg";

??????? var strTempFile?=?localFilePath;

????????//?創(chuàng)建XML對象,組合XML文檔數(shù)據(jù)

??????? var xml_dom?=?UploadForIE.createDocument();

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

????????//?創(chuàng)建ADODB.Stream對象

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

????????//?設(shè)置流數(shù)據(jù)類型為二進制類型

??????? ado_stream.Type?=?1;?// adTypeBinary

????????//?打開ADODB.Stream對象

??????? ado_stream.Open();

????????//?將本地文件裝載到ADODB.Stream對象中

??????? ado_stream.LoadFromFile(strTempFile);

????????//?獲取文件大?。ㄒ宰止?jié)為單位)

??????? var byte_size?=?ado_stream.Size;

????????//?設(shè)置數(shù)據(jù)傳輸單元大小為1KB

??????? var byte_unit?=?1024;

????????//?獲取文件分割數(shù)據(jù)單元的數(shù)量

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

?

????????//?創(chuàng)建XML元素節(jié)點,保存上傳文件名稱

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

??????? node.text?=?upload_filename.toString();

??????? var root?=?xml_dom.documentElement;

??????? root.appendChild(node);

?

????????//?創(chuàng)建XML元素節(jié)點,保存上傳文件大小

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

??????? node.text?=?byte_size.toString();

??????? root.appendChild(node);

?

????????//?創(chuàng)建XML元素節(jié)點,保存上傳文件內(nèi)容

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

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

????????????//?文件內(nèi)容編碼方式為Base64

??????????? node.dataType?=?"bin.base64";

????????????//?判斷當前保存的數(shù)據(jù)節(jié)點大小,根據(jù)條件進行分類操作

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

????????????????//?當數(shù)據(jù)包大小不是數(shù)據(jù)單元的整數(shù)倍時,讀取最后剩余的小于數(shù)據(jù)單元的所有數(shù)據(jù)

??????????????? node.nodeTypedValue?=?ado_stream.Read();

????????????}?else?{

????????????????//?讀取一個完整數(shù)據(jù)單元的數(shù)據(jù)

??????????????? node.nodeTypedValue?=?ado_stream.Read(byte_unit);

????????????}

??????????? root.appendChild(node);

????????}

?

????????//?關(guān)閉ADODB.Stream對象

??????? ado_stream.Close();

??????? delete ado_stream;

????????//?創(chuàng)建Microsoft.XMLHTTP對象

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

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

????????//?打開Microsoft.XMLHTP對象

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

????????//?使用Microsoft.XMLHTP對象上傳文件

??????? 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;

????},

?

????//?創(chuàng)建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)?{

????????????????//跳過

??????????????? alert("創(chuàng)建document對象失?。?);

????????????}

????????}

????????return?xmldom;

????}

}

?

UEditorAction保存圖片方法

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

????????//?設(shè)置數(shù)據(jù)傳輸單元大小為1KB

????????int?unit_size?=?1024;

????????//?初始化xml文件大?。ㄒ宰止?jié)為單位)

????????int?xmlFileSize?=?0;

????????//?初始化上傳文件名稱(完整文件名)

??????? String xmlFilename?=?"";

????????//?初始化上傳文件保存路徑(絕對物理路徑)

??????? String xmlFilepath?=?"";

????????//?聲明文件存儲字節(jié)數(shù)組

????????byte[]?xmlFileBytes?=?null;

????????try?{

????????????//?初始化 SAX 串行xml文件解析器

??????????? SAXBuilder builder?=?new?SAXBuilder();

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

??????????? Element eRoot?=?doc.getRootElement();

????????????//?獲取上傳文件的完整名稱

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

????????????if?(it_name.hasNext())?{

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

????????????}

????????????//存放的相對路徑目錄

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

??????????? xmlFilepath?=?rootPath+?relativePath;

?

????????????//?獲取上傳文件的大小

??????????? 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;

????????????????????//?為存儲文件內(nèi)容的字節(jié)數(shù)組分配存儲空間

??????????????????? xmlFileBytes?=?new?byte[xmlFileSize];

????????????????????//?循環(huán)讀取文件內(nèi)容,并保存到字節(jié)數(shù)組中

??????????????????? Iterator it_content?=?eRoot.getChildren("uploadContent")

????????????????????????????.iterator();

????????????????????while?(it_content.hasNext())?{

????????????????????????//?初始化Base64編碼解碼器

??????????????????????? BASE64Decoder base64?=?new?BASE64Decoder();

????????????????????????byte[]?xmlNodeByteArray?=?base64

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

????????????????????????????????????????.getText());

????????????????????????if?(xmlNodeByteArray.length?>=?unit_size)?{

????????????????????????????//?讀取一個完整數(shù)據(jù)單元的數(shù)據(jù)

??????????????????????????? System.arraycopy(xmlNodeByteArray,?0,?xmlFileBytes,

??????????????????????????????????? unit_count?*?unit_size,?unit_size);

????????????????????????}?else?{

????????????????????????????//?讀取小于一個數(shù)據(jù)單元的所有數(shù)據(jù)

??????????????????????????? System.arraycopy(xmlNodeByteArray,?0,?xmlFileBytes,

??????????????????????????????????? unit_count?*?unit_size,?xmlFileSize

????????????????????????????????????????????%?unit_size);

????????????????????????}

????????????????????????//?繼續(xù)向下讀取文件內(nèi)容

??????????????????????? unit_count++;

????????????????????}

????????????????}

????????????}

?

????????????//?保存路徑

??????????? File path?=?new?File(xmlFilepath);

????????????if(!path.exists()){

??????????????? path.mkdirs();

????????????}

????????????//?保存文件 word粘貼圖片的名稱

??????????? File file?=?new?File(path,xmlFilename);

????????????//?創(chuàng)建文件輸入輸出流

??????????? FileOutputStream fos?=?new?FileOutputStream(file);

????????????//?寫入文件內(nèi)容

??????????? fos.write(xmlFileBytes);

??????????? fos.flush();

????????????//?關(guān)閉文件輸入輸出流

??????????? fos.close();

?

??????????? ReturnUploadImage rui?=?new?ReturnUploadImage();

??????????? rui.setTitle(xmlFilename);//這里需要設(shè)置文件名稱如:xxx.jpg

??????????? rui.setOriginal(xmlFilename);//這里需要設(shè)置文件名稱如:xxx.jpg

??????????? rui.setState("SUCCESS");

??????????? rui.setUrl(basePath?+relativePath+xmlFilename);

?

??????????? JSONObject json?=?new?JSONObject(rui);

????????????String result?=?json.toString();//這邊就是為了返回給UEditor做的格式轉(zhuǎn)換

??????????? response.getWriter().write(result);

????????}?catch?(Exception e)?{

??????????? e.printStackTrace();

????????}

????}

優(yōu)化后的代碼:

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

/*?

????更新記錄:

??????? 2013-01-25?取消對SmartUpload的使用,改用commons-fileupload組件。因為測試發(fā)現(xiàn)SmartUpload有內(nèi)存泄露的問題。

*/

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

{//?處理文件尺寸過大異常?

??? out.println("上傳文件異常:"+e.toString());

????return;

??

}

?

FileItem imgFile =?null;

//?得到所有上傳的文件

Iterator fileItr = files.iterator();

//?循環(huán)處理所有文件

while?(fileItr.hasNext())

{

????//?得到當前文件

??? imgFile = (FileItem) fileItr.next();

????//?忽略簡單form字段而不是上傳域的文件域(<input type="text" />等)

????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()+"");//返回Content-length標記,以便控件正確讀取返回地址。

%>

?

剩下的后臺功能和js參考下載文件中的UEditorAction 和 uploadForIE.js。

下面是我安裝的依賴pom結(jié)構(gòu),可以根據(jù)自己的進行調(diào)整。

? <dependency>

??????????? <groupId>com.baidu</groupId>

??????????? <artifactId>ueditor</artifactId>

??????????? <version>1.1.0</version>

??????? </dependency>

?

基于springboot 和idea ,這里只提取了自動轉(zhuǎn)存功能出來,功能還沒測試,git代碼沒做公開,等后續(xù)測試好了再公開。

可以先使用csdn下載查看代碼。

pom里引用了ueditor.jar

需要根據(jù)各自情況安裝jar包

1.4.2中的jar包版本是1.1.0

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

運行

UeditorApplication的main方法

然后訪問http://localhost:8088/ueditor/ 就可以測試了。

?

完成后的效果:

圖片自動批量上傳,不需要手動一張張選擇圖片上傳,用戶體驗比百度ueditor自帶的更好,傳圖效率更高。

?

?

上傳成功后,圖片地址自動替換成服務(wù)器地址

?

?

圖片自動保存在服務(wù)器中

?

?

詳細資料可以參考這篇文章:

Ueditor Word圖片轉(zhuǎn)存交互 – 澤優(yōu)軟件博客

?

討論群:223813913

?

本文摘自 :https://www.cnblogs.com/

開通會員,享受整站包年服務(wù)立即開通 >