使用HTML元素中的数据创建Javascript Blob().然后将其下载为文本文件 [英] Creating Javascript Blob() with data from HTML Element. Then downloading it as a text file

查看:122
本文介绍了使用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"元素,然后自动单击它,那么它在理论上应该可以正常工作.显然,我虽然错过了一些东西.任何帮助都将是极好的.该网站上的第一个问题btw: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().然后将其下载为文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆