文件API - Blob到JSON

时间:2012-10-08 17:45:43

标签: javascript json html5 websocket

我正在尝试使用HTML5,WebSocket和File API进行一些实验。 我正在使用Tomcat7 WebSocket实现。 我能够从servlet发送和接收短信。我现在要做的是从servlet发送到客户端JSON对象,但我想避免文本消息,以便跳过客户端上的JSON.parse(或类似),所以我试图发送二进制消息。 servlet部分非常简单:

String s = "{arr : [1,2]}";
CharBuffer cbuf = CharBuffer.wrap(s);      
CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder();      
getWsOutbound().writeBinaryMessage(encoder.encode(cbuf));
getWsOutbound().flush();

在此消息之后,在客户端上,我看到我收到了一个二进制帧,它被转换为Blob对象(http://www.w3.org/TR/FileAPI/#dfn-Blob)。 问题是:是否可以从Blob获取JSON对象? 我看了一下FileReader接口(http://www.w3.org/TR/FileAPI/#FileReader-interface),我用这样的代码来检查FileReader可以做什么(第一行创建一个全新的Blob,所以你可以随时测试你想要的) :

var b = new Blob([{"test": "toast"}], {type : "application/json"});
var fr = new FileReader();
fr.onload = function(evt) {
    var res = evt.target.result;
    console.log("onload",arguments, res, typeof res);
};
fr.readAsArrayBuffer(b);

使用我在File Reader实现中看到的所有“readAs ...”方法(我使用的是Chrome 22)。无论如何,我没有找到有用的东西。

你有什么建议吗?感谢。

4 个答案:

答案 0 :(得分:10)

您应该尝试readAsText()而不是readAsArrayBuffer()(JSON最后是文字)。

您还错过了对对象进行字符串化(转换为JSON文本)

var b = new Blob([JSON.stringify({"test": "toast"})], {type : "application/json"}),
    fr = new FileReader();

fr.onload = function() {
    console.log(JSON.parse(this.result))
};

fr.readAsText(b);

答案 1 :(得分:8)

你所做的事情在概念上是错误的。 JSON是对象的字符串表示,而不是对象本身。因此,当您通过网络发送JSON的二进制表示时,您将发送该字符串的二进制表示。没有办法在客户端解析JSON以将JSON字符串转换为JavaScript对象。

您绝对应该始终将JSON作为文本发送到客户端,并且您应该始终调用JSON.parse。没有别的事情对你来说很容易。

答案 2 :(得分:1)

要将包含 JSON 数据的 Blob/File 转换为 JavaScript 对象,请使用它:

JSON.parse(await blob.text());

例子:

选择一个 JSON 文件,然后您可以在浏览器的控制台(json 对象)中使用它。

const input = document.createElement("input");
input.type = "file";
input.accept = "application/json";
document.body.append(input);
input.addEventListener("change", async event => {
    const json = JSON.parse(await input.files[0].text());

    console.log("json", json);
    globalThis.json = json;
});

答案 3 :(得分:0)

let reader = new FileReader()
      reader.onload = e => {
        if (e.target.readyState === 2) {
          let res = {}
          if (window.TextDecoder) {
            const enc = new TextDecoder('utf-8')
            res = JSON.parse(enc.decode(new Uint8Array(e.target.result))) //转化成json对象
          } else {
            res = JSON.parse(String.fromCharCode.apply(null, new Uint8Array(e.target.result)))
          }

          console.info('import-back:: ', res)


        }
      }

      reader.readAsArrayBuffer(response)