How do I write “raw” bytes to the browser in JavaScript?

僤鯓⒐⒋嵵緔 提交于 2020-07-22 06:09:25

问题


I am trying to serve a PDF file to the user, and I have a string containing the bytes in the PDF file. I want to write these bytes to the browser so the user can download the PDF file. However when I do this:

document.open('application/pdf');
document.write(myBytes);

I just get the bytes rendered as text, that is, they are in an HTML page (see screenshots). I want only the bytes specified to be rendered, without any HTML surrounding them. How can I do this?


回答1:


You can force file download with anchor && download attribute trick or use iframe

Here's an example below

Snippet doesn't work because of sandboxed environment.

const pdfView = document.querySelector("#pdfView");

fetch("https://cors-anywhere.herokuapp.com/https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf")
  .then(response => response.blob())
  .then(blob => blob.arrayBuffer())
  .then(myBytes => {
    const totalBlob = new Blob([myBytes], { type: 'application/pdf' });
    const url = window.URL.createObjectURL(totalBlob);
    const anchor = document.createElement("a");
    anchor.href = url;
    anchor.download = `document.pdf`;
    anchor.click();
    anchor.textContent = 'Download'
    document.body.appendChild(anchor);

    pdfView.src = url;  
  })
<iframe id="pdfView" src="" type="application/pdf" width="100%" height="100%" style="overflow: auto;">
    </iframe>


来源:https://stackoverflow.com/questions/62437177/how-do-i-write-raw-bytes-to-the-browser-in-javascript

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!