Will the file become larger after Swoole receives the binary data and saves the file?

scenario: use websocket to upload and save files.
Business description: the client uses H5 websocket to upload binary files, and the server uses Swoole WS service to receive the files and save them.
question: why does the size of the saved file on the server get bigger?

client code:

ws.onmessage = function(e) {
        console.log(e.data);
        log(":" + e.data + ""\n");
        if (e.data == "connect ok") {
            //
            log("");
        } 


            var file = document.getElementById("myFile").files[0];
            var obj = {
                "name": file.name,
                "size": file.size,
                "type": file.type
            }

            var reader = new FileReader(); 

           //
            reader.readAsBinaryString(file);

            reader.onload = function(e) {
                obj.data = e.target.result;
                var data = JSON.stringify(obj);
                ws.send(data);
                log("...");
            }
    }

server:

public function onMessage(swoole_websocket_server $ws, $frame)
    {
        $data = json_decode($frame->data, true);

        $ext = pathinfo($data["name"], PATHINFO_EXTENSION);

        $filename = "./files/".time().".". $ext;

        $tmp = $data["data"];

        file_put_contents($filename, $tmp); //
        echo "file path : {$filename}\n";
        //$ws->push($frame->fd, "upload success");
    }

start the server, and then after the client selects the image file, the websocket connection is normal, send the file, and the server receives the data, but when I save the data, I save the received data as an image file. I found that the picture size has become larger, the source picture is 5.4KB, and the picture uploaded to the server has 8KB, that is, the size has changed, and the saved picture is not normal and cannot be opened.

I tried to upload a text file and found that the size was normal and the saved file was normal. Somehow.

Feb.18,2022

 var data = JSON.stringify(obj);

you have converted binary data into strings. Your client should use base64 code to transfer binary. After receiving it on the server side, base64 decoding is stored

.
Menu