基于kindeditor实现批量粘贴word文档中图片到富文本中

 1、编写公共js

判断是否需要替换图片
function replaceImage(originUrl) {
    if (originUrl.indexOf('file://') > -1) {
        return true; //本地文件替换
    } else if (originUrl.indexOf('https://docimg2.docs.qq.com') > -1) {
        return false; //来自腾讯文档不替换
    }
};

//判断是mac还是window
function getPosType() {
    var agent = navigator.userAgent.toLowerCase();
    var isMac = /macintosh|mac os x/i.test(navigator.userAgent);
    if (agent.indexOf('win32') >= 0 || agent.indexOf('wow32') >= 0) {
        return 'win';
    }
    if (agent.indexOf('win64') >= 0 || agent.indexOf('wow64') >= 0) {
        return 'win';
    }
    if (navigator.userAgent.indexOf('Intel Mac') > 0) {
        return 'x64Mac'; //'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36'
    } else {
        return 'arm64Mac';
    }
}

//base64图片转成文件流格式
function base64ToFile(data, fileName) {
    const dataArr = data.split(',');
    const byteString = atob(dataArr[1]);
    const options = {
        type: 'image/jpeg',
        endings: 'native',
    };
    const u8Arr = new Uint8Array(byteString.length);
    for (let i = 0; i < byteString.length; i++) {
        u8Arr[i] = byteString.charCodeAt(i);
    }
    let formData = new FormData();
    let fileOfBlob = new File([u8Arr], fileName ? fileName : new Date().getTime() + '.jpg', options); //返回文件流
    formData.append('upload', fileOfBlob);
    return formData;
}

//反斜杠转斜杠
function backslashToSlash(val) {
    return val.replace(/\\/g, '/');
}

//协议是否注册。有注册就打开
customProtocolCheckFunc = (val) => {
	//https://gitee.com/xoobom/wpspaster/releases
    window.customProtocolCheck(val,(err) => {
            window.open('/download-wpspaster.jsp', '_blank');
        },
        (res) => { },
        500
    );
};

//处理富文本粘贴word图片
function initEditor(editorId,callBack){
    const socket = io("http://localhost:9001", {
        transports: ['websocket'], //不加这个会跨域
        autoConnect: true, //是否自动连接
        reconnection: false, //关闭重连
    });
    let newImgUrlListAll = [];
    socket.on("getImgByLocal", function (res1) {
        // let url ='http://xoobom.com:8023/file/upload'
        let url ='../common/kindeditor!jQueryFileUpload.action?dir=download-center'
        axios.post(
            url,
            base64ToFile(res1.data.base64)).then(function (res2) {
            let prefix = ['x64Mac', 'arm64Mac'].includes(getPosType()) ? 'file:/' : 'file:///';//kindeditor的话mac是file:/,win是file://
            newImgUrlListAll.push({
                originUrl: prefix + res1.data.filePath,//kindeditor是file://
                url: '/'+res2.data[0].url,
            });
        })
    });

    socket.on('connect_error', (error) => {
            customProtocolCheckFunc('wpspaster://');//协议是否注册。有注册就打开
    });
    // 'wordpaster',   'map',  'flash',
    var editor = KindEditor.create(editorId, {
        width: '100%',
        height: '300px',
        uploadJson: "../common/kindeditor!kindeditorUpload.action?",
        allowFileManager: true,
        formatUploadUrl: false,
        newlineTag: 'p',
        items: [
            'source', '|', 'undo', 'redo', '|', 'preview', 'print', 'template', 'cut', 'copy', 'paste',
            'plainpaste', 'wordpaste','|', 'justifyleft', 'justifycenter', 'justifyright',
            'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript',
            'superscript', 'clearhtml', 'quickformat', 'selectall', '|', 'fullscreen', '/',
            'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold',
            'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|', 'image',
            'media', 'insertfile', 'table', 'hr', 'emoticons', 'code', 'pagebreak',
            'link', 'unlink', '|', 'about'],
        afterBlur:callBack,
        filterMode: false,
        pasteType: 2,
        afterCreate: function () {
            var self = this;
            // 监听ctrl+v事件
            self.edit.doc.body.addEventListener('keydown', function (e) {
                if (e.keyCode == 86) {
                    setTimeout(()=>{
                        const htmlString = self.html();
                        const div = document.createElement('div');
                        div.innerHTML = htmlString;
                        let newImgUrlList = div.getElementsByTagName('img');

                        if (newImgUrlList.length > 0) {
                            for (let i = 0; i < newImgUrlList.length; ++i) {
                                if (replaceImage(newImgUrlList[i].src)) {
                                    console.log('newImgUrlList')
                                    let filePath = ['x64Mac', 'arm64Mac'].includes(getPosType()) ? newImgUrlList[i].src.slice(6) : newImgUrlList[i].src.slice(8);
                                    socket.emit('getImgByLocal', {
                                        'filePath': filePath,
                                    });
                                }
                            }
                        }
                    }, 10);
                }
            });
            // 监听浏览器鼠标右键粘贴事件
            self.edit.doc.body.addEventListener('paste', function (e) {
                setTimeout(()=>{
                    const htmlString = self.html();
                    const div = document.createElement('div');
                    div.innerHTML = htmlString;
                    let newImgUrlList = div.getElementsByTagName('img');

                    if (newImgUrlList.length > 0) {
                        for (let i = 0; i < newImgUrlList.length; ++i) {
                            if (replaceImage(newImgUrlList[i].src)) {
                                console.log('newImgUrlList')
                                let filePath = ['x64Mac', 'arm64Mac'].includes(getPosType()) ? newImgUrlList[i].src.slice(6) : newImgUrlList[i].src.slice(8);
                                socket.emit('getImgByLocal', {
                                    'filePath': filePath,
                                });
                            }
                        }
                    }
                }, 10);
            });
        }
    });

    //Object.create返回一个新对象,新对象的_proto_就是传进去的参数 js原生监听数组的方法
    let newProtetype = Object.create(Array.prototype);
    let methods = ["push", "pop", "shift", "unshift", "reserve", "sort", "splice"];
    methods.forEach(function (method) {
        //新原型上添加同名[method] ,返回原来的Array.prototype[method]
        newProtetype[method] = function (...args){
            let content = editor.html();
            setTimeout( ()=> {
                if (newImgUrlListAll.length > 0) {
                if (replaceImage(newImgUrlListAll[0].originUrl)) {
                    content = content.replace(
                        /<img [^>]*src=['"]([^'"]+)[^>]*>/gi,
                        function (mactch, capture) {
                            let current = '';
                            for (let i = 0; i < newImgUrlListAll.length; i++) {
                                let sourcePath = '';//粘贴原路径
                                if (getPosType() == 'win') {
                                    sourcePath = backslashToSlash(capture.replace(/(&amp;)/gi, '&'));
                                } else {
                                    sourcePath = capture.replace(/(&amp;)/gi, '&');
                                }
                                if (sourcePath == newImgUrlListAll[i].originUrl) {
                                    current = newImgUrlListAll[i].url;
                                    break;
                                }
                            }
                            current = current ? current : capture;
                            return mactch.replace(
                                /src=[\'\"]?([^\'\"]*)[\'\"]?/i,
                                'src=' + current,
                            );
                        });
                    editor.html(content);
                }
            } // 匹配并替换 img中src图片路径
        },10);
            return Array.prototype[method].call(this,...args);
        }
    })
    //绑定新的原型
    newImgUrlListAll.__proto__ = newProtetype;
}
//处理富文本粘贴word图片--end

2、页面中应用如下 

//富文初始化
        initEditor('#content', function() {
            this.sync();
            //手动重新验证
            var bv = $("#addInfoForm").data('bootstrapValidator');
            bv.revalidateField("jobInfo.content");
        })

 该项目在可在码云搜到wpspaster: 🚀 图文一键粘贴软件,支持从Word、WPS图文复制后一键粘贴到Tinymce、CKEditor、UEditor、KindEditor等富文本编辑器。支持Chrome、360、Edge、Firefox等现代浏览器。适用Window、Mac (gitee.com)

 以下图片展示的是相关控件,该控件是收费的

 

1. 首先,在 `application\extra` 目录下新建一个 `config.php` 文件,添加以下配置: ```php <?php return [ 'upload_path' => '/uploads/', //上传文件保存的路径 'upload_exts' => 'gif,jpg,jpeg,png,bmp', //允许上传的文件类型 ]; ``` 2. 在 `application\index\controller` 目录下新建一个 `Upload.php` 控制器,添加以下代码: ```php <?php namespace app\index\controller; use think\Controller; use think\Request; class Upload extends Controller { public function uploadImage() { $file = request()->file('imgFile'); $info = $file->validate(['ext' => config('upload_exts')])->move(ROOT_PATH . 'public' . config('upload_path')); if ($info) { $image_url = config('upload_path') . $info->getSaveName(); return json(['error' => 0, 'url' => $image_url]); } else { return json(['error' => 1, 'message' => $file->getError()]); } } } ``` 3. 在 `application\index\view` 目录下新建一个 `upload_image.html` 文件,添加以下代码: ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>上传图片</title> </head> <body> <form action="<?php echo url('upload/uploadImage'); ?>" enctype="multipart/form-data" method="post"> <input type="file" name="imgFile"> <input type="submit" value="上传"> </form> </body> </html> ``` 4. 修改 `kindeditor` 配置文件 `public\static\kindeditor\config.js`,添加以下代码: ```javascript //上传图片配置 imageUploadJson = '<?php echo url("upload/uploadImage"); ?>'; ``` 5. 在 `public\static\kindeditor\plugins` 目录下新建一个 `image.php` 文件,添加以下代码: ```php <?php //获取上传文件保存的路径 $save_path = $_SERVER['DOCUMENT_ROOT'] . $_POST['save_path']; //获取要上传的文件 $file = $_FILES['imgFile']; //上传文件 if (move_uploaded_file($file['tmp_name'], $save_path . $file['name'])) { $image_url = $_POST['base_url'] . $_POST['save_path'] . $file['name']; //返回上传结果 echo json_encode(['error' => 0, 'url' => $image_url]); } else { echo json_encode(['error' => 1, 'message' => '上传失败']); } ``` 6. 修改 `kindeditor` 的 `php` 上传文件处理程序 `public\static\kindeditor\php\upload_json.php`,添加以下代码: ```php //获取要保存的文件路径和文件名 $save_path = $_SERVER['DOCUMENT_ROOT'] . $_POST['save_path']; $file_name = uniqid() . strrchr($_FILES['imgFile']['name'], '.'); //上传文件 if (move_uploaded_file($_FILES['imgFile']['tmp_name'], $save_path . $file_name)) { $image_url = $_POST['base_url'] . $_POST['save_path'] . $file_name; //返回上传结果 echo json_encode(['error' => 0, 'url' => $image_url]); } else { echo json_encode(['error' => 1, 'message' => '上传失败']); } ``` 7. 在浏览器访问 `http://localhost/index/upload_image.html`,上传一张图片测试。如果上传成功,会返回图片的 URL 地址。在 `kindeditor` 也可以正常上传图片了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值