然后将其下载为文本文件

然后将其下载为文本文件

本文介绍了使用来自 HTML 元素的数据创建 Javascript Blob().然后将其下载为文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 HTML5 站点在 textarea 元素中创建一个日志.我需要通过单击按钮从该区域提取数据,然后通过 .txt 文件将其下载到我的计算机.如果可能的话,我将如何去做?

I'm using an HTML5 site to create a log per-say within a textarea element. I need to pull the data from that area with the click of a button, and download it to my computer via a .txt file. How would I go about doing this if it is possible??

HTML:

<input type="button" onclick="newBlob()" value="Clear and Export">

Javascript:

Javascript:

function newBlob() {
    var blobData = document.getElementById("ticketlog").value;
    var myBlob = new Blob(blobData, "plain/text");
    blobURL = URL.createObjectURL(myBlob);
    var href = document.createElement("a");
    href.href = blobURL;
    href.download = myBlob;
    href.id = "download"
    document.getElementById("download").click();
}

我想如果我制作了 Blob,为它创建一个 URL,将 URL 映射到一个a"元素,然后自动点击它,理论上它应该可以工作.显然我错过了一些东西.任何帮助都会很棒.本网站的第一个问题顺便说一句:p

I figure if I make the Blob, create a URL for it, map the URL to an "a" element then auto-click it then it should work in theory. Obviously I'm missing something though. Any help would be fantastic. 1st question on this site btw:p

推荐答案

我想到的最简单的方法如下:

The simplest way I've come up with is as follows:

function download(text, filename){
  var blob = new Blob([text], {type: "text/plain"});
  var url = window.URL.createObjectURL(blob);
  var a = document.createElement("a");
  a.href = url;
  a.download = filename;
  a.click();
}

download("this is the file", "text.txt");

可能的 blob 文件类型列表:http://www.freeformatter.com/mime-types-list.html

List of possible blob filestypes: http://www.freeformatter.com/mime-types-list.html

这篇关于使用来自 HTML 元素的数据创建 Javascript Blob().然后将其下载为文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 01:52