Eclipse-
Eclipse-

Reputation: 71

How can I save a buffer created by express-fileupload to a file?

I want to post this image to my nodejs express server using express-fileupload, this is my node code:

app.post("/files", function(req, res) {
    console.log(req.files.brandLogo)

    const data = {
            fieldname: 'file',
            originalname: req.files.brandLogo.name,
            encoding: req.files.brandLogo.encoding,
            mimetype: req.files.brandLogo.mimetype,
            buffer: req.files.brandLogo.data,
            size: req.files.brandLogo.size
    };

    fs.writeFile("file", data, function(err) {
        if(err) {
            return console.log(err);
        }
        console.log("The file was saved!");
    });
});

I can see the file posted being logged into the console, name, size, and everything is correct, but when I try to write this buffer to a file, the written file is a 1kb file and not the correct one. Any ideas? Cheers.

Upvotes: 1

Views: 3556

Answers (1)

Terry Lennox
Terry Lennox

Reputation: 30705

I would suggest making a simple change to use JSON.stringify when writing to the output file, like so:

app.post("/files", function(req, res) {
    console.log(req.files.brandLogo)

    const data = {
            fieldname: 'file',
            originalname: req.files.brandLogo.name,
            encoding: req.files.brandLogo.encoding,
            mimetype: req.files.brandLogo.mimetype,
            buffer: req.files.brandLogo.data,
            size: req.files.brandLogo.size
    };

    // Use JSON.stringify to serialize here.
    fs.writeFile("file", JSON.stringify(data, null, 4), function(err) {
        if(err) {
            return console.log(err);
        }
        console.log("The file was saved!");
    });
});

Otherwise the data is converted to something like "[object Object]", which is not what we want!

Upvotes: 1

Related Questions