Javascript:从页面内的内容下载数据到文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4184944/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:17:16  来源:igfitidea点击:

Javascript: Download data to file from content within the page

javascriptfiledownloadlocal

提问by Simon

setting is the following: I have a homepage where I display a diagram that has been constructed using comma seperated values from within the page. I'd like to give users the possibility to download the data as cvs-file without contacting the server again. (as the data is already there) Is this somehow possible? I'd prefer a pure JavaScript solution.

设置如下: 我有一个主页,我在其中显示了一个图表,该图表使用页面内的逗号分隔值构建。我想让用户无需再次联系服务器就可以将数据下载为 cvs 文件。(因为数据已经存在)这有可能吗?我更喜欢纯 JavaScript 解决方案。

So far I've discovered: http://pixelgraphics.us/downloadify/test.htmlbut it involves flash which I'd like to avoid.

到目前为止,我发现:http: //pixelgraphics.us/downloadify/test.html但它涉及我想避免的闪存。

I can't imagine this question hasn't been asked before. I'm sorry to double post, but it seems I've used the wrong keywords or something - I haven't found a solution in these forums.

我无法想象以前没有人问过这个问题。我很抱歉重复发帖,但似乎我使用了错误的关键字或其他东西 - 我在这些论坛中没有找到解决方案。

采纳答案by scunliffe

Update:

更新

Time certainly changes things ;-) When I first answered this question IE8was the latest IE browser available (Nov 2010) and thus there was no cross browser way to accomplish this without a round trip to the server, or using a tool requiring Flash.

时间肯定会改变事情 ;-) 当我第一次回答这个问题时,IE8是可用的最新 IE 浏览器(2010 年 11 月),因此没有跨浏览器的方式来实现这一点,而无需往返服务器或使用需要 Flash 的工具。

@Zectburno's answerwill get you what you need now, however for historical context be aware of which IE browsers support which feature.

@Zectburno 的回答将为您提供您现在需要的东西,但是对于历史背景,请注意哪些 IE 浏览器支持哪些功能。

  • btoa() is undefined in IE8 and IE9
  • Blob is available in IE10+
  • btoa() 在 IE8 和 IE9 中未定义
  • Blob 在 IE10+ 中可用

Be sure to test in the browsers you need to support. Even though the Blob example in the other answer should work in IE10+ it doesn't work for me just clicking the link (browser does nothing, no error)... only if I right click and save target as "file.csv" then navigate to the file and double-click it can I open the file.

请务必在您需要支持的浏览器中进行测试。即使另一个答案中的 Blob 示例应该在 IE10+ 中工作,但仅单击链接对我不起作用(浏览器什么也不做,没有错误)......只有当我右键单击并将目标另存为“file.csv”然后导航到该文件并双击它可以打开该文件。

Test both approaches (btoa/Blob) in this JSFiddle.(here's the code)

在此 JSFiddle 中测试这两种方法(btoa/Blob)。(这是代码)

<!doctype html>
<html>
<head>
</head>
<body>
  <a id="a" target="_blank">Download CSV (via btoa)</a>
  <script>
    var csv = "a,b,c\n1,2,3\n";
    var a = document.getElementById("a");
    a.href = "data:text/csv;base64," + btoa(csv);
  </script>
  <hr/>
  <a id="a2" download="Download.csv" type="text/csv">Download CSV (via Blob)</a>
  <script>
    var csv = "a,b,c\n1,2,3\n";
    var data = new Blob([csv]);
    var a2 = document.getElementById("a2");
    a2.href = URL.createObjectURL(data);
  </script>
</body>
</html>

Original Answer:

原答案

I don't think there is an option available for this.

我认为没有可用的选项。

I would just adjust your code such that if Flash 10+ is detected (93% saturation as of September 2009) on the user's system, provide the Downloadify option, otherwise fallback to a server-side request.

我只会调整您的代码,以便如果在用户系统上检测到 Flash 10+(截至 2009 年 9 月的饱和度为 93%),请提供 Downloadify 选项,否则回退到服务器端请求。

回答by Zectbumo

Tested on Safari 5, Firefox 6, Opera 12, Chrome 26.

在 Safari 5、Firefox 6、Opera 12、Chrome 26 上测试。

<a id='a'>Download CSV</a>
<script>
    var csv = 'a,b,c\n1,2,3\n';
    var a = document.getElementById('a');
    a.href='data:text/csv;base64,' + btoa(csv);
</script>


HTML5

HTML5

<a id='a' download='Download.csv' type='text/csv'>Download CSV</a>
<script>
    var csv = 'a,b,c\n1,2,3\n';
    var data = new Blob([csv]);
    var a = document.getElementById('a');
    a.href = URL.createObjectURL(data);
</script>

回答by Yassir Ennazk

Simple solution :

简单的解决方案:

function download(content, filename, contentType)
{
    if(!contentType) contentType = 'application/octet-stream';
        var a = document.createElement('a');
        var blob = new Blob([content], {'type':contentType});
        a.href = window.URL.createObjectURL(blob);
        a.download = filename;
        a.click();
}

Usage

用法

download("csv_data_here", "filename.csv", "text/csv");

回答by Blowsie

function export(exportAs) {
    var csvText = tableRowsToCSV(this.headTable.rows);-
    csvText += tableRowsToCSV(this.bodyTable.rows);-
    //open the iframe doc for writing
    var expIFrame;
    if (strBrowser == "MSIE") expIFrame = document.exportiframe;
    else expIFrame = window.framesexportiframe;
    var doc = expIFrame.document;
    doc.open('text/plain', 'replace');
    doc.charset = "utf-8";
    doc.write(csvText);
    doc.close();
    var fileName = exportAs + ".txt";
    doc.execCommand("SaveAs", null, fileName);
}

function tableRowsToCSV(theRows) {
    var csv = "";
    var csvRow = "";
    var theCells;
    var cellData = "";
    for (var r = 0; r < theRows.length; r++) {
        theCells = theRows.item(r).cells;
        for (var c = 0; c < theCells.length; c++) {
            cellData = "";
            cellData = theCells.item(c).innerText;
            if (cellData.indexOf(",") != -1) cellData = "'" + cellData + "'";
            if (cellData != "") csvRow += "," + cellData;
        }
        if (csvRow != "") csvRow = csvRow.substring(1, csvRow.length);-
        csv += csvRow + "\n";
        csvRow = "";
    }
    return csv;
}

I found this code elsewhere, here, previously

我在别处找到了这个代码,这里,以前

回答by Pekka

As far as I know, this is not possible: This is why Downloadify was created.

据我所知,这是不可能的:这就是创建 Downloadify 的原因。

You could try linking to a data:URLcontaining CSV data, but there will be cross-browser trouble.

您可以尝试链接到data:URL包含 CSV 数据的链接,但会出现跨浏览器问题。

回答by Andrew Ho

The most comprehensive solution I have run across is using FileSaver.js, handling many potential cross-browser issues for you with fallbacks.

我遇到的最全面的解决方案是使用FileSaver.js,通过回退为您处理许多潜在的跨浏览器问题。

It takes advantage of the Blobobject as other posters have done, and the creator even creates a Blob.jspolyfill in case you need to support browser versions that don't support Blob

Blob像其他海报一样利用了对象,创建者甚至创建了一个Blob.js polyfill,以防您需要支持不支持的浏览器版本Blob

回答by Joe Sarre

If your users have up to date browsers, the new Blob object could help you.

如果您的用户拥有最新的浏览器,新的 Blob 对象可以帮助您。

Based on the example here https://developer.mozilla.org/en/docs/DOM/Blob("Blob constructor example usage"), you could do something like the following:

基于此处的示例https://developer.mozilla.org/en/docs/DOM/Blob(“Blob构造函数示例用法”),您可以执行以下操作:

var typedArray = "123,abc,456"; //your csv as a string
var blob = new Blob([typedArray], {type: "text/csv"});
var url = URL.createObjectURL(blob);
var a = document.querySelector("#linktocsv"); // the id of the <a> element where you will render the download link
a.href = url;
a.download = "file.csv";

回答by Sneg

HTML:

HTML:

<a href="javascript:onDownload();">Download</a>

JavaScript:

JavaScript:

function onDownload() {
    document.location = 'data:Application/octet-stream,' +
                         encodeURIComponent(dataToDownload);
}

Taken from How to Download Data as a File From JavaScript

取自如何从 JavaScript 将数据下载为文件