Joe*_*oey 43 javascript html5 blob
我有一个名为Blob()的字符串:
var mystring = "Hello World!";
var myblob = new Blob([mystring], {
type: 'text/plain'
});
mystring = "";
Run Code Online (Sandbox Code Playgroud)
如何取回字符串?
function getBlobData(blob) {
// Not sure what code to put here
}
alert(getBlobData(myblob)); // should alert "Hello World!"
Run Code Online (Sandbox Code Playgroud)
Phi*_*ipp 50
要从Blob中提取数据,您需要一个FileReader.
var reader = new FileReader();
reader.onload = function() {
alert(reader.result);
}
reader.readAsText(blob);
Run Code Online (Sandbox Code Playgroud)
21r*_*1rw 24
你可以使用该blob.text()方法。
blob.text().then(text => {
let blobText = text
})
Run Code Online (Sandbox Code Playgroud)
它将以 UTF-8 编码返回 blob 的内容。请注意,它必须处于异步状态。
Pau*_* S. 14
如果浏览器支持它,您可以通过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;
}
Run Code Online (Sandbox Code Playgroud)
然后
var b = new Blob(['hello world']);
blobToString(b); // "hello world"
Run Code Online (Sandbox Code Playgroud)
kpg*_*kpg 14
@joey询问了如何将@philipp的答案包装在一个函数中,所以这是一个在现代Javascript中做到这一点的解决方案(感谢@Endless):
const text = await new Response(blob).text()
Run Code Online (Sandbox Code Playgroud)
小智 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'
Run Code Online (Sandbox Code Playgroud)