vue前端页面使用mammoth进行word文档的预览。
1、引入mammoth.js
安装依赖:
npm install --save mammoth
2、配置
webpack5以上需要对polyfill进行配置,如果是5一下,则不用进行此项配置。
2.1 安装依赖:
npm install --save util
npm install --save path-browserify
2.2 添加配置
然后在webpack.config.js(或者vue.config.js)中添加如下内容:
module.exports = {
configureWebpack: config => {
config.resolve
.fallback= {
util: require.resolve("util/"),
path: require.resolve("path-browserify")
};
}
}
2.3 配置Buffer
在main.js中添加如下内容,避免Buffer is not defined异常:
import * as buffer from "buffer";
if (typeof window.Buffer === "undefined") {
window.Buffer = buffer.Buffer;
}
3、读取word内容
配置完成后,可以进行word内容的读取预览。
3.1 导入
import mammoth from 'mammoth'
3.2 添加读取方法
previewFile() {
let _this=this;
try {
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:9000/doc/a.docx", true);
xhr.responseType = "arraybuffer";
xhr.onload = function(e) {
if (xhr.status === 200) {
mammoth
.convertToHtml({ arrayBuffer: new Uint8Array(xhr.response) })
.then(result => {
// 读取到的内容
console.log(result.value);
})
.done();
return;
}
console.log(e);
};
xhr.send();
} catch (e) {
console.log(e);
}
},
Comments NOTHING