今天一个需求富文本能直接用word导入,好嘛,应该行,网上找了下案例基本都是先上传后台再返回html,后端忙就纯自己写了 手写富文本用的是tinymce这个就不介绍了 烂大街了
然后用word转html 这个重点 添加依赖
npm install --save mammoth
不用全局引入哪里需要哪里引入
import mammoth from "mammoth"; //word预览依赖
html
<span class="p-r" style="margin-left:15px;">
<el-button size="small" type="primary" >导入word</el-button>
<input type="file" ref="document" id="document" class="p-a" style="top:0;left:0;backgroud:red;width:80px;opacity: 0;cursor: pointer;" />
</span>
mounted() {
//添加事件监听器
this.$refs.document.addEventListener("change", this.readFileInputEventAsArrayBuffer, true)
},
beforeDestroy(){
//移除事件监听器
this.$refs.document.removeEventListener("change", this.readFileInputEventAsArrayBuffer, true)
} ,
methods
//word转html
readFileInputEventAsArrayBuffer(event) {
let target = this.$refs.document;
let file = target.files[0];
console.log(file);
//判断文件类型代码
let fileType = [".docx"];
let { name } = file;
let nameLen = name.length;
let hzIndex = name.lastIndexOf(".");
//获取后缀名
let hz = name.substring(hzIndex, nameLen);
if (!fileType.includes(hz)) {
this.$message.warning({
message: "注意:导入word只支持docx格式的文档",
})
return false
}else{
this.$message.success({
message: "导入成功",
})
}
var that = this
var reader = new FileReader();
reader.onload = function (loadEvent) {
console.log(loadEvent.target.result);
var arrayBuffer = loadEvent.target.result;//arrayBuffer
mammoth.convertToHtml({ arrayBuffer: arrayBuffer })
.then(
function (resultObject) {
tinymce.activeEditor.setContent(resultObject.value) //富文本插入代码命令
console.log(resultObject.value);//这个就是我们得到的html
//document.body.innerHTML = resultObject.value
}
//that.displayResult()
)
.done();
};
reader.readAsArrayBuffer(file);
},}
得到的结果就能直接是html了 图片也给你转成base64了 赞的