从 Javascript 中的 BLOB URL 中读取数据
Read data from BLOB URL in Javascript
我有一个 BLOB URL,我想将它重新创建为第二个 BLOB URL,以便默认下载它。
var blob1 = new Blob(["Hello world!"], { type: "text/plain" });
url1 = window.URL.createObjectURL(blob1);
blob2=new Blob([url1], {type: 'application/octet-stream'});
url2 = window.URL.createObjectURL(blob2);
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
a.href = url2;
a.click();
window.URL.revokeObjectURL(url);
参见 JSFiddle:
https://jsfiddle.net/7spry3jn/
但这只会创建一个包含第一个 URL 的文本文件。如何从 Javascript 中的第一个 BLOB URL 中读取数据并将其提供给创建第二个 BLOB?
您可以在 anchor
元素中使用 download
属性,这会强制下载并且您不需要重新创建另一个 blob。
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
:
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>
我有一个 BLOB URL,我想将它重新创建为第二个 BLOB URL,以便默认下载它。
var blob1 = new Blob(["Hello world!"], { type: "text/plain" });
url1 = window.URL.createObjectURL(blob1);
blob2=new Blob([url1], {type: 'application/octet-stream'});
url2 = window.URL.createObjectURL(blob2);
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
a.href = url2;
a.click();
window.URL.revokeObjectURL(url);
参见 JSFiddle:
https://jsfiddle.net/7spry3jn/
但这只会创建一个包含第一个 URL 的文本文件。如何从 Javascript 中的第一个 BLOB URL 中读取数据并将其提供给创建第二个 BLOB?
您可以在 anchor
元素中使用 download
属性,这会强制下载并且您不需要重新创建另一个 blob。
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
:
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>