質問

I am using websockets for file transfer, while i am downloading a file i am recieving the data as it is, but when I open an image file it was corrupted. Data files are downloading fine, the code goes as follows.

try {
    fileEntry = fs.root.getFile(filename, { create : creat_file });
    var byteArray = new Uint8Array(data.data.length);
    for (var i = 0; i < data.data.length; i++) {
        byteArray[i] = data.data.charCodeAt(i) & 0xff;
    }
    BlobBuilderObj = new WebKitBlobBuilder();
    BlobBuilderObj.append(byteArray.buffer);
    if (!writer) {
        writer = fileEntry.createWriter();
        pos = 0;
    }
    //self.postMessage(writer.position);
    writer.seek(pos);
    writer.write(BlobBuilderObj.getBlob());
    pos += 4096;
    }
catch (e) {
    errorHandler(e);
}
役に立ちましたか?

解決

It looks like you are reading data from a WebSocket as a string, converting it to a Blob, and then writing this to a file.

If you have control of the WebSocket server then the best thing would be to send the data as binary frames instead of UTF-8 text data. If you can get the server to send the data as binary frames then you can just tell the WebSocket to deliver the data as Blobs:

ws.binaryType = "blob";
ws.onmessage = function (event) {
    if (event.data instanceof Blob) {
        // event.data is a Blob
    } else {
        // event.data is a string
    }
}

If that is not an option and you can only send text frames from the server, then you will need to encode the binary data to text before sending it from the server and then decode the text on the other end. If you try and send binary data directly as text frames over WebSockets then doing charCodeAt(x) && 0xff will result in corrupt data.

For example you could base64 encode the data at the server and then base64 decode the data in the client:

ws.onmessage = function (event) {
    raw = window.atob(event.data);
}

Update:

There is a very well performing pure Javascript base64 decode/encode contained in websockify. It decodes to an an array of numbers from 0-255 but could be easily modified to return a string instead if that is what you require (Disclaimer: I made websockify).

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top