更新时间:2023-12-04 16:08:52
您可以在anchor
元素中使用download
attr,这将强制下载,并且您不需要重新创建另一个Blob.
You can use the download
attr in anchor
element, that force the download and you dont need to reate another blob.
但是您需要注意有关浏览器的支持,请在此处查看所有接受
download
attr的浏览器:我可以使用
But you need to pay attentio about browser support, see here all the browsers that accept the
download
attr: Can I Use
var blob1 = new Blob(["Hello world!"], { type: "text/plain" });
url = window.URL.createObjectURL(blob1);
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
a.href = url;
a.setAttribute("download","Any name");
a.click();
window.URL.revokeObjectURL(url);
要从Blob
中读取内容,您可以像这样使用FileReader
:
And to read the content from a Blob
you can use FileReader
like this:
var myBlob = new Blob(["Hello"], {type : "text/plain"});
var myReader = new FileReader();
//handler executed once reading(blob content referenced to a variable) from blob is finished.
myReader.addEventListener("loadend", function(e){
document.getElementById("text").innerHTML = e.srcElement.result;//prints a string
});
//start the reading process.
myReader.readAsText(myBlob);
<p id="text"></p>