在Javascript中从BLOB URL读取数据

时间:2016-02-27 13:28:44

标签: javascript url download blob

我有一个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?

1 个答案:

答案 0 :(得分:6)

你可以在download元素中使用anchor attr强制下载,你不需要再创建另一个blob。

  

但您需要关注浏览器支持,请参阅此处接受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>