peq42
peq42

Reputation: 402

How to write a file sent via websocket?

I'm making a server sistem in which the server uploads files to a client via websockets. The server is corretly sending the file, but I don't know how to write it in the client side.

I've tried receiving the file data using "msg", "msg.data" and many other ways, but it always result in a 1kb file. I also tried converting the file to base64 before sending and converting back in the client side(so the message would be text instead of a binary), but didn't work.

Server:

var ws = require("nodejs-websocket")
ws.setBinaryFragmentation(99999999999)
var fs   = require('fs'),  
    file = process.argv[2],
    data = fs.readFileSync("./map.zip");

    var server = ws.createServer(function (connection) { 

connection.sendBinary(data)
    }).listen(1000)

Client:

var connection = new WebSocket("ws://localhost:1000")

connection.onmessage=function(msg){
    var fs=require("fs")
    fs.writeFileSync("./test.zip",msg.data)
}

Upvotes: 0

Views: 1230

Answers (1)

Daniel
Daniel

Reputation: 11182

I think you should consider sticking to your base64 encoding approach, as binary files are a hell to debug.

Send it as base64 and receive it from the client with

var connection = new WebSocket("ws://localhost:1000")

connection.onmessage=function(msg){
    var fs=require("fs")
    let buffer = new Buffer(msg.data);
    fs.writeFileSync("test.zip", buffer);
}

(This assumes that msg.data is a base64 encoded binary file)

Upvotes: 1

Related Questions