从Java中的BLOB URL读取数据 [英] Read data from BLOB URL in Javascript

查看:85
本文介绍了从Java中的BLOB URL读取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个BLOB URL,我想将其重新创建为第二个BLOB URL,以便默认情况下将其下载.

I have a BLOB URL, and I want to recreate it as a second BLOB URL, so that it is downloaded by default.

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:

See in JSFiddle:

https://jsfiddle.net/7spry3jn/

但这只会创建一个包含第一个URL的文本文件.如何从Javascript中的第一个BLOB URL读取数据并将其提供以创建第二个BLOB?

But this only creates a text file containint the first URL. How can I Read data from the first BLOB URL in Javascript and feed it to create the second BLOB?

推荐答案

您可以在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 downloadattr: 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>

这篇关于从Java中的BLOB URL读取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆