Search code examples
node.jsimageexpressbufferform-data

How could I save an img in my express server that I receive from my client?


I have a client in React that sends a form data with a file. When that file arrives to the server, the body is parsed by body parser and its result is a buffer. The idea is that the file keep saved in some place of my server, because I want to use it later from my client. So I'd like to know how should I handle this problem.

I tried to write directly this buffer as a file with fs, but the file created has an error of format, so I can't access it.


Solution

  • You can do stuff like this

    var fs = require('fs');
    fs.writeFile('newImage', req.files.image, function (err) {
       if (err) throw err;
       console.log("It's saved");
    });
    

    correct parameter order of fs.writeFile is the filename first then the content.

    If you're using express.bodyParser() you'll have the uploaded files in the req.files field.

    And of course you should write the callback:

    POV: Your image file should be in req.files not the body.