由於工作需要必須將word文檔內容粘貼到編輯器中使用
但發現word中的圖片粘貼后變成了file:///xxxx.jpg這種內容,如果上傳到服務器后其他人也訪問不了,網上找了很多編輯器發現沒有一個能直接解決這個問題
考慮到自己除了工作其他時間基本上不使用windows,因此打算使用nodejs來解決這一問題
發現不管什么編輯器只要將圖片轉換成base64后就可以直接使用(IE8及一下可能不支持),由於編輯器中添加word文檔功能也只是自己用,因此可以忽略這種瀏覽器了
找了很久,試用了很多編輯器,發現只有ckeditor的功能還算符合我的需求(支持自定義HTML屬性)
然后我寫了一個監聽粘貼事件的操作,用來獲取粘貼之后的file:///xxxx.jpg這種路徑
<script>
var service = {
http : require('http'),
url : require('url'),
querystring : require('querystring'),
fs : require('fs'),
config : {
timeout : 60000,
charset : 'utf8',
port : 10101,
host : '127.0.0.1'
},
router : {
index : function(res, query){
res.end('Server is running!');
},
check : function(res, query){
var result = {status: 1, info: 'success'};
result = JSON.stringify(result);
if(typeof query.callback == 'string'){
result = query.callback + '(' + result + ')';
}
res.end(result);
},
word : function(res, query){
var _this = service;
var result = {status: 0, info: 'error'};
if(typeof query.file == 'string'){
var img = query.file.match(/file:\/\/+(localhost)?(\S+\.(png|jpg|jpeg|gif|bmp))/i);
console.log(img);
if(img){
var base64 = _this.base64_encode(img[2]);
result.status = 1;
result.info = 'data:image/' + img[3] + ';base64,' + base64;
}
}
result = JSON.stringify(result);
if(typeof query.callback == 'string'){
result = query.callback + '(' + result + ')';
}
res.end(result);
}
},
start : function(){
var _this = this;
var Server = _this.http.createServer(function (req, res) {
var URL = _this.url.parse(req.url);
var receive = [];
var router = null;
switch(URL.pathname){
case '/word':
router = _this.router.word;
break;
case '/check':
router = _this.router.check;
break;
default:
router = _this.router.index;
}
req.setEncoding(_this.config.charset);
req.addListener('data', function(data) {
receive.push(data);
});
res.writeHead(200, {'Content-Type': 'text/plain'});
res.on("close",function(){
console.log("res closed");
});
req.on("close",function(){
console.log("req closed");
});
req.addListener('end', function() {
router(res, _this.querystring.parse(URL.query));
});
});
Server.listen(_this.config.port, _this.config.host, 1024);
Server.setTimeout(_this.config.timeout, function(cli){
cli.end('timeout\n');
});
console.log('Server running at http://' + _this.config.host + ':' + _this.config.port);
},
//base64
base64_encode : function(file){
var bitmap = this.fs.readFileSync(file);
return new Buffer(bitmap).toString('base64');
}
};
service.start();
</script>
將以上代碼保存為一個word.js文件
然后執行 node word.js就會自動創建一個http服務了
這個時候我們在編輯器中使用jsonp獲取到處理完的圖片數據替換原來的file:///xxxxxx.jpg路徑就搞定了
處理word圖片批量上傳的代碼
其它的業務邏輯參數代碼
當然也可以將以上代碼打包成一個本地執行文件去給不懂電腦的人使用就行了(具體方法我這里就不說了)
前台引用的代碼
下面是實現后的效果,能夠自動上傳Word中的所有圖片,並且有進度條顯示
所有圖片都能夠保存在服務器中,而且支持分布式圖片存儲
編輯器中的圖片地址已經全部替換成了服務器的圖片地址,其它的用戶也能夠正常訪問
詳細內容可以參考這篇文章:http://blog.ncmem.com/wordpress/2019/07/30/ckeditor%e7%b2%98%e8%b4%b4word/