Javascript - 我从字符串创建了一个blob,如何将字符串取回?

时间:2014-04-12 00:02:37

标签: javascript html5 blob

我有一个名为Blob()的字符串:

var mystring = "Hello World!";
var myblob = new Blob([mystring], {
    type: 'text/plain'
});
mystring = "";

如何取出字符串?

function getBlobData(blob) {
    // Not sure what code to put here
}
alert(getBlobData(myblob)); // should alert "Hello World!"

5 个答案:

答案 0 :(得分:43)

要从Blob中提取数据,您需要FileReader

var reader = new FileReader();
reader.onload = function() {
    alert(reader.result);
}
reader.readAsText(blob);

答案 1 :(得分:13)

如果浏览器支持它,您可以通过blob URI XMLHttpRequest 来进行

function blobToString(b) {
    var u, x;
    u = URL.createObjectURL(b);
    x = new XMLHttpRequest();
    x.open('GET', u, false); // although sync, you're not fetching over internet
    x.send();
    URL.revokeObjectURL(u);
    return x.responseText;
}

然后

var b = new Blob(['hello world']);
blobToString(b); // "hello world"

答案 2 :(得分:5)

试试:

var mystring = "Hello World!";
var myblob = new Blob([mystring], {
    type: 'text/plain'
});
mystring = "";
outurl = URL.createObjectURL(myblob);
fetch(outurl)
.then(res => res.text())
.then(data => {
    console.log(data)
})

//'Hello World'

答案 3 :(得分:4)

@joey询问了如何将@philipp的答案包装在一个函数中,因此这是一个在现代Javascript中做到这一点的解决方案(感谢@Endless):

const text = await new Response(blob).text()

答案 4 :(得分:0)

您可以使用 blob.text() 方法。

blob.text().then(text => {
  let blobText = text
})

它将以 UTF-8 编码返回 blob 的内容。 请注意,它必须处于异步状态。