最近想做一個預覽的效果,爬文後目前是找到mammoth的方式,爬了很多文都是用上傳檔案後(也就是input type="file"的方式),偵測名字變化後取得event.target.files再丟到arraybuffer裡來讀取檔案,但是我今天想要做的是,按下預覽按鈕後可以直接呈現出檔案內容(排版也不會完全跑掉),像下面圖片
如果想使用按按鈕直接預覽該怎麼做呢?像是這個效果
https://xiaotianxia.github.io/blog/vuepress/js/word_preview.html
以下是我目前的程式碼
showfile.ejs
<!DOCTYPE html>
<html>
<head>
<!-- <title><%= title %></title> -->
<link rel='stylesheet' href='/stylesheets/style.css' />
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<p id="demo"></p>
<div class="container">
<input id="document" type="file" />
<div class="row">
<div class="span8">
<div id="output" class="well">
</div>
</div>
</div>
<script>
var list = "<%= filelist %>".split(",");//從別的地方傳進來的
list.forEach(myFunction);
function myFunction(item, index) {
var lists = document.getElementById("demo").innerHTML += index + ":" + item + "<button id ='see' value=" + item + " >預覽</button>" + "<br>";
}
</script>
<script src="https://cdn.bootcss.com/mammoth/1.4.8/mammoth.browser.js"></script>
<script src="demo.js"></script>
</body>
</html>
demo.js
(function() {
document.getElementById("document")
.addEventListener("change", handleFileSelect, false);
function handleFileSelect(event) {
readFileInputEventAsArrayBuffer(event, function(arrayBuffer) {
mammoth.convertToHtml({arrayBuffer: arrayBuffer})
.then(displayResult)
.done();
});
}
function displayResult(result) {
document.getElementById("output").innerHTML = result.value;
}
function readFileInputEventAsArrayBuffer(event, callback) {
var file = event.target.files[0];
var reader = new FileReader();
console.log("callback:"+callback);
reader.onload = function(loadEvent) {
var arrayBuffer = loadEvent.target.result;
callback(arrayBuffer);
};
reader.readAsArrayBuffer(file);
}
})();
有嘗試過:
1.改成:mammoth.convertToHtml({path: 路徑}) 但會報錯Uncaught Error: Could not find file in options
可以用 ajax 取得檔案的 arrayBuffer
之後就照你原先的方式丟給 mammoth 處理
例如:
html
<button class='preview' data-url='{這邊填docx檔連結}'>預覽</button>
javascript
function preview(evt)
{
var btn=evt.target;
var url=btn.dataset['url'];
var xhr=new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType='arraybuffer';
xhr.onreadystatechange=function (){
if(this.readyState==4){
if(this.status==200){
var arrayBuffer=this.response;
console.log(arrayBuffer);
} else {
console.log(this.status);
}
}
}
xhr.send();
}
(function(){
document.querySelectorAll('.preview').forEach(function(btn){
btn.addEventListener('click', preview);
});
})();