问题描述
我的代码中有一条非常简单的行,应该触发在旅途中创建的文件的下载。
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楼
dilusha_dasanayaka
2
已采纳
2019-02-25 05:31:07
试试这个解决方案
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支持,有关更多选项,请查看此问题的 。