文件 API - Blob 到 JSON [英] File API - Blob to JSON

查看:16
本文介绍了文件 API - Blob 到 JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to do some experiment with HTML5, WebSocket and File API. I'm using the Tomcat7 WebSocket implementation. I'm able to send and received text messages from the servlet. What I want to do now is to send from the servlet to the client JSON objects, but I want to avoid text message in order to skip the JSON.parse (or similar) on the client, so I'm trying to send binary messages. The servlet part is really simple:

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,因此您可以根据需要进行动态测试):

After this message, on the client I see that I received a binary frame, that is converted to a Blob object (http://www.w3.org/TR/FileAPI/#dfn-Blob). The question is: is it possible to get the JSON object from the Blob? I took a look at the FileReader interface (http://www.w3.org/TR/FileAPI/#FileReader-interface), and I used code like this to inspect what the FileReader can do (the first line creates a brand new Blob, so you can test on the fly if you want):

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);

使用我在文件阅读器实现中看到的所有readAs..."方法(我使用的是 Chrome 22).反正我没找到有用的东西.

using all the "readAs..." methods that I saw on the File Reader implementation (I'm using Chrome 22). Anyway I didn't find something useful.

你有什么建议吗?谢谢.

Did you have any suggestion? Thanks.

推荐答案

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

What you're doing is conceptually wrong. JSON is a string representation of an object, not an object itself. So, when you send a binary representation of JSON over the wire, you're sending a binary representation of the string. There's no way to get around parsing JSON on the client side to convert a JSON string to a JavaScript Object.

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

You absolutely should always send JSON as text to the client, and you should always call JSON.parse. Nothing else is going to be easy for you.

这篇关于文件 API - Blob 到 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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