关于利用vue对word进行读取,并解析到页面上

     关于word上传大家很多都会想到上传文件到后端,后端进行解析word,并返回目录和内容到前端中去,这个也是一个方法。

     前端解析word,速度更快,但是在替换代码的时候也非常的麻烦,但是可以降低http的响应速度,不用调接口,页面响应速度很快,上代码

<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
 
<body>
    <div class="container">
        <input id="document" type="file" />
        <div id="output"></div>
    </div>
    <script src="https://cdn.bootcss.com/mammoth/1.4.8/mammoth.browser.js"></script>
    <script>
        // mammothJs只能读取docx文件~所以打开word后先另存为docx(文件类型选择Word文档选项)格式
        document.querySelector('#document').addEventListener('change',readFileInputEventAsArrayBuffer,true)
        function showResult(result) {
            console.log(result);
            let html = result.value;
            // console.log(html);
            // // 将解析出来的dom元素的展示替换成自己想要的样子
            let newHTML = html.replace(/<strong>目录/g, '')
              const newNum= newHTML.indexOf("h")
              let endHTML=newHTML.substring(0,newNum-1)
              console.log(endHTML);
            // 将解析出来的html展示在页面上
            document.querySelector('#output').innerHTML=newHTML
        }
 
        function readFileInputEventAsArrayBuffer(event) {
            var file = event.target.files[0];
            var reader = new FileReader();
 
            reader.onload = function (loadEvent) {
                console.log(loadEvent);
                var arrayBuffer = loadEvent.target.result; // arrayBuffer     
                // mammothJs
                mammoth.convertToHtml({ arrayBuffer: arrayBuffer })
                    .then(res => showResult(res));
            };
 
            reader.readAsArrayBuffer(file);
        }
 
 
    </script>
</body>
 
</html>

上传代码的时候会经常报错,经常报错是

 Can't find end of central directory : is this a zip file ? If it is, see http://stuk.github.io/jszip/documentation/howto/read_zip.html

这个其实是因为word文档格式的错误,应该到wps或者是word文件中,进行文档的转化,不要随便的更改后缀

----代码借鉴这个小伙伴的

【js】Mammoth.js的使用:将.docx 文件转换成HTML_mammoth js_陪着月亮的博客-CSDN博客

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值