【问题标题】:Javascript - I created a blob from a string, how do I get the string back out?Javascript - 我从一个字符串创建了一个 blob,如何将字符串取出?
【发布时间】:2014-05-26 07:25:54
【问题描述】:

我有一个名为 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!"

【问题讨论】:

    标签: javascript html blob


    【解决方案1】:

    为了从 Blob 中提取数据,您需要一个 FileReader

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

    【讨论】:

    • 那么我怎样才能将它包装在一个函数中并让它返回结果呢?
    • 好吧,我把它包装在一个函数中。但由于某种原因,它仅在我第二次尝试访问它时才有效:jsfiddle.net/vMrF5
    • @Joey 那是因为竞争条件。异步加载发生在后台。第一次还没有加载,第二次可能已经加载了。但是,不要依赖于此!这是未定义的行为,会因执行而异。你完全无法判断加载需要多长时间。
    • 如果其他人想将其包装在一个函数中,请参阅下面的答案。
    【解决方案2】:

    @joey 询问如何将@philipp 的答案包装在一个函数中,所以这是一个在现代 Javascript 中执行此操作的解决方案(感谢@Endless):

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

    【讨论】:

    • 如果你想把它作为一个承诺,那就做const text = await new Repsponse(blob).text()
    【解决方案3】:

    如果浏览器支持它,你可以通过一个 blob URIXMLHttpRequest

    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"
    

    【讨论】:

    • 这有点 hacky,难道没有不那么 hacky 的方法吗?
    • 这可行,但 chrome 76 现在警告弃用 [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.
    • 是的,它在 FireFox '85.0.2 (64-bit)' XML Parsing Error: not well-formed Location: blob:http://localhost:4200/40be6ace-691c-43a2-b208-824a0d0a933 Line Number 1, Column 1 我的 'Angular 6' 应用程序中出现错误。为了解决这个需要添加类型,const b = new Blob(['hello world'], { type: 'text/plain' });
    【解决方案4】:

    试试:

    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'
    

    【讨论】:

    【解决方案5】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-12
      • 1970-01-01
      • 2014-06-27
      • 1970-01-01
      • 2011-07-24
      • 2013-08-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多