如何通过Websocket发送arraybuffer作为二进制文件?

时间:2012-03-03 13:20:07

标签: javascript file-upload websocket binary arraybuffer

我正在与Mozilla Europe合作开展一个项目。在这个项目中,我使用了Worlize(服务器端)和Mozilla(客户端)的websocket,Node.js尝试将文件从客户端上传到服务器。 我目前的目标是将arraybuffer文件发送到服务器。创建arraybuffer并发送它很好 但我的服务器告诉我arraybuffer是一个utf8消息而不是二进制消息。

我误解了什么吗?如果没有,我该如何纠正?

客户方:

    reader = new FileReader();
    reader.readAsArrayBuffer(file);
    reader.onload = function(e) {
        connection.send(e.target.result); 
    };

服务器端:

ws.on('message', function(message,flags) {
if (!flags.binary) {
    //some code
}
else {
    console.log('It\'s a binary');
}

我也尝试Blob,同样的结果。二进制部分是不可见的。

2 个答案:

答案 0 :(得分:22)

Gecko11.0 ArrayBuffer已经实现了对二进制数据的发送和接收支持。

connection = new WebSocket('ws://localhost:1740');
connection.binaryType = "arraybuffer";
connection.onopen = onopen;
connection.onmessage = onmessage;
connection.onclose = onclose;
connection.onerror = onerror;

发送二进制数据:

function sendphoto() {
    imagedata = context.getImageData(0, 0, imagewidth,imageheight);

    var canvaspixelarray = imagedata.data;


    var canvaspixellen = canvaspixelarray.length;
    var bytearray = new Uint8Array(canvaspixellen);

    for (var i=0;i<canvaspixellen;++i) {
        bytearray[i] = canvaspixelarray[i];
    }

    connection.send(bytearray.buffer);
    context.fillStyle = '#ffffff';
    context.fillRect(0, 0, imagewidth,imageheight);    
}

收到二进制数据:

if(event.data instanceof ArrayBuffer)
    {

        var bytearray = new Uint8Array(event.data);


        var tempcanvas = document.createElement('canvas');
            tempcanvas.height = imageheight;
            tempcanvas.width = imagewidth;
        var tempcontext = tempcanvas.getContext('2d');

        var imgdata = tempcontext.getImageData(0,0,imagewidth,imageheight);

        var imgdatalen = imgdata.data.length;

        for(var i=8;i<imgdatalen;i++)
        {
            imgdata.data[i] = bytearray[i];
        }

        tempcontext.putImageData(imgdata,0,0);


        var img = document.createElement('img');
            img.height = imageheight;
            img.width = imagewidth;
            img.src = tempcanvas.toDataURL();
        chatdiv.appendChild(img);
        chatdiv.innerHTML = chatdiv.innerHTML + "<br />";
    }

答案 1 :(得分:1)

Note: Prior to version 11, Firefox only supported sending data as a string.

来源:https://developer.mozilla.org/en/WebSockets/Writing_WebSocket_client_applications