如何下载新创建的HTML文件?

时间:2019-11-30 10:04:34

标签: javascript html

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

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

我想下载这个新创建的HTML文档。我尝试过:

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

但是不起作用。它将我重定向到myDomain.com/[object HTMLDocument]。如何下载此文件?

3 个答案:

答案 0 :(得分:2)

几个阶段。

  1. 将文档的HTML放入Blob中。
  2. 将blob转换为blob网址
  3. 创建一个链接以下载此URL

下面的例子。

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>

答案 1 :(得分:0)

您不能在filename中附加URL,因为使用HTML File 创建的createHTMLDocument()不是实际的HTML文件,并且不是服务器上的 Javascript HTMLDocument对象

您可以使用Data URI,如下所示,Complete Tutorial Here..

function download(filename, text) {
  var element = document.createElement('a');
  element.setAttribute('href', 'data:text/html;charset=utf-8,' + encodeURIComponent(text));
  element.setAttribute('download', filename);

  element.style.display = 'none';
  document.body.appendChild(element);

  element.click();

  document.body.removeChild(element);
}

// Start file download.
download("newDoc.html","<html><head><title>Hello</title></head><body>Hello World!</body></html>");

  

注意:下载后,功能encodeURIComponent()不会影响HTML。

答案 2 :(得分:0)

function download(filename, text) {
  var element = document.createElement('a');
  element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
  element.setAttribute('download', filename);

  element.style.display = 'none';
  document.body.appendChild(element);

  element.click();

  document.body.removeChild(element);
}


// Start file download.
function myFunction(){
  let html = document.getElementById("textarea").value;;
  download("hello.html", html); 
}
<textarea id="textarea" placeholder="Type your HTML here..."><h1>WORKING?????</h1></textarea>

<button onclick="myFunction()">GET FILE</button>