iT邦幫忙

0

javascript預覽問題

最近想做一個預覽的效果,爬文後目前是找到mammoth的方式,爬了很多文都是用上傳檔案後(也就是input type="file"的方式),偵測名字變化後取得event.target.files再丟到arraybuffer裡來讀取檔案,但是我今天想要做的是,按下預覽按鈕後可以直接呈現出檔案內容(排版也不會完全跑掉),像下面圖片
https://ithelp.ithome.com.tw/upload/images/20200405/201257442PsPvax3KB.png

如果想使用按按鈕直接預覽該怎麼做呢?像是這個效果
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

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

2
淺水員
iT邦大師 6 級 ‧ 2020-04-05 12:37:53

可以用 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);
    });
})();

您好,謝謝您的解答,想請問一下,console.log(arrayBuffer)的結果是undefined是正常的嗎?
url確定是有東西的,按下去會自動下載一個word檔,代表路徑沒有問題
感謝解惑><

淺水員 iT邦大師 6 級 ‧ 2020-04-06 00:32:58 檢舉

var arrayBuffer=this.response; 才對,剛剛修正了。

可以運行,真是太感謝你了!!

0
Leo
iT邦新手 3 級 ‧ 2020-04-05 15:40:51

我建議你可以考慮限制檔案上傳格式為 PDF ,然後預覽的時候用 PDF.js 來呈現會更為輕鬆且有效

我要發表回答

立即登入回答