Home > Back-end >  How could I save an img in my express server that I receive from my client?
How could I save an img in my express server that I receive from my client?

Time:01-20

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.

CodePudding user response:

I think you need a package for storing a file on your backend service. I had used morgan package for that and I was satisfied with using it. I have just searched other packages for storing a file, i found express-fileupload package. Maybe you want to look at how to use those. If you want to store a file, using the third package would be better for you and for your effort.

CodePudding user response:

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.

  • Related