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.

3
  • On the client I would suspect that you will need to upload it as binary data rather than using utf-8 encoding, see stackoverflow.com/questions/48994269/… (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 (npmjs.com/package/busboy). Commented Mar 29, 2020 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? Commented Mar 29, 2020 at 12:50
  • @abondoa I have tried sending a string and that is received correctly. I will try with a txt file Commented Mar 29, 2020 at 13:21

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.