Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
293 views
in Technique[技术] by (71.8m points)

javascript - 如何下载新创建的HTML文件?(How to download newly created HTML file?)

I create an HTML file with document.implementation.createHTMLDocument() function.

(我使用document.implementation.createHTMLDocument()函数创建一个HTML文件。)

Like so:

(像这样:)

 var doc = document.implementation.createHTMLDocument("My New Document");

And I want to download this newly create HTML document.

(我想下载这个新创建的HTML文档。)

I tried this:

(我尝试了这个:)

var link = document.createElement('a');
link.href = doc;
link.download = 'newDoc.html';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);

But doesn't work.

(但是不起作用。)

It redirects me to myDomain.com/[object HTMLDocument] .

(它将我重定向到myDomain.com/[object HTMLDocument] 。)

How can I download this file?

(如何下载此文件?)

  ask by 12318867 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A Couple of stages.

(几个阶段。)

  1. Place the HTML of the document into a blob,.

    (将文档的HTML放入Blob。)

  2. Convert blob into a blob url

    (将Blob转换为Blob网址)

  3. Create a link to download this url

    (创建一个链接来下载此URL)

Example below..

(下面的例子)

 const bt = document.querySelector('button'); bt.addEventListener('click', () => { //lets create some document const doc = document.implementation.createHTMLDocument("My New Document"); const hello = doc.createElement('p'); hello.innerText = 'Hello'; doc.body.appendChild(hello); //now get it's contents and place into a blob const blob = new Blob([doc.documentElement.innerHTML], { type: 'text/html' }); //now convert to url const docUrl = window.URL.createObjectURL(blob); //were done, lets create a href to this and download const aclick = document.createElement('a'); aclick.href = docUrl; aclick.download = 'download.html'; aclick.click(); //tidy up window.URL.revokeObjectURL(docUrl); }); 
 <p>Click button below to download some HTML</p> <button>download</button> 


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...