JavaScript:创建并保存文件

use*_*980 246 javascript dialog file save

我有要写入文件的数据,并打开文件对话框供用户选择保存文件的位置.如果它适用于所有浏览器会很棒,但它必须在Chrome中运行.我想在客户端做到这一点.

基本上我想知道在这个函数中放什么:

saveFile: function(data)
{
}
Run Code Online (Sandbox Code Playgroud)

在函数接收数据的情况下,用户是否选择保存文件的位置,并使用该数据在该位置创建文件.

使用HTML也很好,如果有帮助的话.

Kan*_*chu 222

Awesomeness01对代码的一个非常小的改进(不需要锚标记),如trueimage(支持IE)所建议的添加:

// Function to download data to a file
function download(data, filename, type) {
    var file = new Blob([data], {type: type});
    if (window.navigator.msSaveOrOpenBlob) // IE10+
        window.navigator.msSaveOrOpenBlob(file, filename);
    else { // Others
        var a = document.createElement("a"),
                url = URL.createObjectURL(file);
        a.href = url;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        setTimeout(function() {
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);  
        }, 0); 
    }
}
Run Code Online (Sandbox Code Playgroud)

经测试可在Chrome,FireFox和IE10中正常使用.

在Safari中,数据在新选项卡中打开,人们必须手动保存此文件.

  • 我们可以用什么来表示“类型”? (3认同)
  • 下载时如何在此脚本中设置位置? (2认同)

los*_*rce 126

github上的这个项目看起来很有希望:

https://github.com/eligrey/FileSaver.js

FileSaver.js在本机不支持它的浏览器中实现W3C saveAs()FileSaver接口.

另请看这里的演示:

http://eligrey.com/demos/FileSaver.js/

  • http://www.w3.org/TR/file-writer-api/#the-filesaver-interface说"该文件的工作已经停止,不应该被引用或用作实施的基础." (35认同)
  • 正如人们所期望的那样,所有代码都可以在 git 中找到。不确定“那是什么?”的目的是什么?评论是。如果它真的想知道它是什么,那么 https://www.w3.org/TR/file-writer-api/ 会有所帮助。如果它指出项目已取消,则该信息在 git 的 README 中。 (2认同)

Awe*_*s01 120

function download(text, name, type) {
  var a = document.getElementById("a");
  var file = new Blob([text], {type: type});
  a.href = URL.createObjectURL(file);
  a.download = name;
}
Run Code Online (Sandbox Code Playgroud)
<a href="" id="a">click here to download your file</a>
<button onclick="download('file text', 'myfilename.txt', 'text/plain')">Create file</button>
Run Code Online (Sandbox Code Playgroud)

然后,您可以通过将下载属性放在锚标记上来下载文件.

我喜欢这个比创建数据网址更好的原因是你不必创建一个很长的网址,你可以只生成一个临时网址.


Mat*_*eer 38

无法在创建文件之前选择保存文件的位置.但至少在Chrome中,可以使用JavaScript生成文件.这是我创建CSV文件的一个老例子.系统将提示用户下载它.不幸的是,这在其他浏览器中效果不佳,尤其是IE.

<!DOCTYPE html>
<html>
<head>
    <title>JS CSV</title>
</head>
<body>
    <button id="b">export to CSV</button>
    <script type="text/javascript">
        function exportToCsv() {
            var myCsv = "Col1,Col2,Col3\nval1,val2,val3";

            window.open('data:text/csv;charset=utf-8,' + escape(myCsv));
        }

        var button = document.getElementById('b');
        button.addEventListener('click', exportToCsv);
    </script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)


小智 18

setTimeout("create('Hello world!', 'myfile.txt', 'text/plain')");
function create(text, name, type) {
  var dlbtn = document.getElementById("dlbtn");
  var file = new Blob([text], {type: type});
  dlbtn.href = URL.createObjectURL(file);
  dlbtn.download = name;
}
Run Code Online (Sandbox Code Playgroud)
<a href="javascript:void(0)" id="dlbtn"><button>click here to download your file</button></a>
Run Code Online (Sandbox Code Playgroud)


boo*_*r11 15

尝试使用它下载文件,您所要做的就是编辑onclick属性.

function download(text, name, type) {
  var a = document.getElementById("a");
  a.style.display = "block";
  var file = new Blob([text], {type: type});
  a.href = URL.createObjectURL(file);
  a.download = name;
}
Run Code Online (Sandbox Code Playgroud)
#a { display: none; }
Run Code Online (Sandbox Code Playgroud)
<a href="" id="a" download>click here to download your file</a>
<button onclick="download('file text', 'myfilename.txt', 'text/plain')">Create file</button>
Run Code Online (Sandbox Code Playgroud)


小智 15

function download(text, name, type) {
  var a = document.getElementById("a");
  var file = new Blob([text], {type: type});
  a.href = URL.createObjectURL(file);
  a.download = name;
}
Run Code Online (Sandbox Code Playgroud)
<a href="" id="a">click here to download your file</a>
<button onclick="download('file text', 'myfilename.json', 'text/json')">Create file</button>
Run Code Online (Sandbox Code Playgroud)

我认为如果您更改 mime 类型,这也可以与 json 文件一起使用。


pdj*_*ota 13

对于Chrome等最新浏览器,您可以使用本教程中File API:

window.requestFileSystem  = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(window.PERSISTENT, 5*1024*1024 /*5MB*/, saveFile, errorHandler);
Run Code Online (Sandbox Code Playgroud)

  • 我认为[此代码段(http://www.html5rocks.com/en/tutorials/file/filesystem/#toc-file-writing)将接近提问者的意图. (2认同)
  • 请看这里有关它死亡的证据:http://lists.w3.org/Archives/Public/public-webapps/2014AprJun/0010.html (2认同)

Net*_*964 8

在控制台中尝试了这一点,它的工作原理.

var aFileParts = ['<a id="a"><b id="b">hey!</b></a>'];
var oMyBlob = new Blob(aFileParts, {type : 'text/html'}); // the blob
window.open(URL.createObjectURL(oMyBlob));
Run Code Online (Sandbox Code Playgroud)


小智 8

function SaveBlobAs(blob, file_name) {
    if (typeof navigator.msSaveBlob == "function")
        return navigator.msSaveBlob(blob, file_name);

    var saver = document.createElementNS("http://www.w3.org/1999/xhtml", "a");
    var blobURL = saver.href = URL.createObjectURL(blob), 
        body = document.body;

    saver.download = file_name;

    body.appendChild(saver);
    saver.dispatchEvent(new MouseEvent("click"));
    body.removeChild(saver);
    URL.revokeObjectURL(blobURL);
}
Run Code Online (Sandbox Code Playgroud)


Aam*_*mir 6

你不能纯粹用Javascript来做这件事.由于安全原因,在浏览器上运行的Javascript还没有足够的权限(有提案).

相反,我建议使用Downloadify:

一个小的javascript + Flash库,可以在没有服务器交互的情况下创建和下载文本文件.

您可以在此处看到一个简单的演示,您可以其中提供内容并可以测试保存/取消/错误处理功能.