安装docx-preview
npm install docx-preview -S
首先接受的是二进制文件流,只支持docx的文件预览export function previewFile(query) { return request({ url: '发请求的地址', method: 'get', params: query, responseType: 'blob' // 声明是流 }) }
发请求后,得到的res
let fileName = ‘下载的文件名’ // 得到文件名 let res = await previewFile({ id: row.id }) let docwindow = window.open("", 'DetailRunTime'); // 创建新窗口 let box = document.createElement('div') // 创建一个div let docx = require("docx-preview") docx.renderAsync(res, box).then(() => { // 渲染文件 docwindow.document.write(box.outerHTML); //渲染文件后将div添加到新窗口中,div不能提前添加,否则新窗口中不能渲染出文件 //注意这里不能直接用box docwindow.document.title = fileName // 窗口标题 docwindow.document.getElementsByClassName('docx')[0].style.width = 'auto' // 如果文件显示正常,不用设置宽度,我的出现了下图所示只显示了一半 })