当前位置: 代码迷 >> JavaScript >> 创建文件并触发Javascript下载
  详细解决方案

创建文件并触发Javascript下载

热度:66   发布时间:2023-06-05 14:03:52.0

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

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"}));`

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

试试这个解决方案

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支持,有关更多选项,请查看此问题的 。

  相关解决方案