0

I am trying to send and receive a file in a typical client/server interaction:

  1. Client sends over a zip file.
  2. Server receives and saves it.

Client

const options = {
    hostname: "localhost",
    port: 8080,
    method: "POST",
    headers: {
        "Content-Type": "application/x-www-form-urlencoded",
        "Content-Length": fs.statSync("C:/users/Public/file.zip").size
    }
};

const clientRequest = http.request(options, res => {
    res.setEncoding('utf8');

    let data = "";
    res.on("data", (chunk) => {
        data += chunk;
    });

    res.on("end", () => {
        console.log(data);
    });
});

const zipFileStream = fs.createReadStream("C:/users/Public/file.zip");

zipFileStream.on("data", data => {
    clientRequest.write(data, "utf-8");
});

zipFileStream.on("end", () => {
    clientRequest.end(() => {
        console.log("Transmitted!");
    });
});

Server

http.createServer((req, res) => {
    req.on("data", (data) => {
        console.log(`Data received: ${data}`);

        const dstDir = "C:/users/Public";
        const dstPath = path.join(dstDir, `zip-${Math.ceil(Math.random()*100000)}.zip`);
        const dstStream = fs.createWriteStream(dstPath);
        dstStream.write(data, "utf-8", (error) => {
            if (error) {
                console.log(`Error while trying to save zip into ${dstPath}: ${error}`);
                return;
            }

            utils.log(`Data written into ${dstPath}`);
        });
    });
}).listen(8080);

The problem

The issue is that everything works fine and the server correctly receives the data and also saves the stream into the specified file. So in the end I get a zip file in the filesystem. When I try to open it:

Windows cannot open the folder. The Compressed (zip) folder "..." is invalid.

Seems like a serialization issue. But I specified the encoding so I thought I had it covered.

Andry
  • 16,172
  • 27
  • 138
  • 246
  • On the client I would suspect that you will need to upload it as binary data rather than using utf-8 encoding, see https://stackoverflow.com/questions/48994269/nodejs-send-binary-data-with-request (he is uploading an image, but I suspsect the same thing applies here). On the server I would advise to use a library for handling file uploads. E.g. busboy (https://www.npmjs.com/package/busboy). – abondoa Mar 29 '20 at 12:48
  • Out of curiosity, have you tried uploading a simple text file (which is utf-8 encoded)? If so, does that get saved correctly? – abondoa Mar 29 '20 at 12:50
  • @abondoa I have tried sending a string and that is received correctly. I will try with a txt file – Andry Mar 29 '20 at 13:21

0 Answers0