创建文件并触发Javascript下载

时间:2019-02-25 04:52:32

标签: javascript

我的代码中有一个非常简单的行,应该触发在旅途中下载的文件的下载。

window.open(window.URL.createObjectURL(new Blob(["Example of something being written into a file then downloaded"], {type: "text/plain"})));

但是由于某些原因,这不起作用。一个新窗口开始出现,然后突然消失。

有什么线索为什么这行不通?

编辑:如果我打电话

`window.location = window.URL.createObjectURL(new Blob(["Example of something being written into a file then downloaded"], {type: "text/plain"}));`

它将打开文件。但是没有下载任何内容。

1 个答案:

答案 0 :(得分:2)

尝试此解决方案

var saveData = (function () {
    var a = document.createElement("a");
    document.body.appendChild(a);

    return function () {
         var data = "Your data...........",
             fileName = "filename";
            blob = new Blob(data, {type: "text/plain"}),
            url = window.URL.createObjectURL(blob);
        a.href = url;
        a.download = fileName;
        a.text = "download file";
        window.URL.revokeObjectURL(url);
    };
}());

这将创建新的<a>元素。您可以通过单击下载文件。

这需要HTML 5支持,并需要更多选项,请检查answers以获得该问题。