Home > Software design >  How to store an html input image file to a file locally on the server
How to store an html input image file to a file locally on the server

Time:09-26

I want to store the image uploaded in a simple html input

<input
      type="file"
      name="thumbnail"
      id="image-input"
      accept="image/png, image/jpg, image/jpeg"
      hidden
 />

This leads to a post request when submitted

router.post('/dish/new',async (req,res) => {
  let { name, desc, cost, isnonveg, thumbnail} = req.body;
  fs.writeFile(path.join(__dirname,'../userdata/images/dishes','g.jpg'),thumbnail, ()=>{
    console.log('image stored')
  })
})

I want to store whatever the user uploads using node fs How can I go about doing this. The approach I use here merely stores the name of the file instead of the actual file.

CodePudding user response:

if you are using express you can add this attribute to form tag enctype="multipart/form-data". Then your image will be sent from frontend . To receive the image in the server you need to configure a middleware called express-fileupload

var fileupload = require("express-fileupload");

then you can register the middleware by app.use(fileupload()); in your app.js file

in your route file

    router.post('/something', async (req, res) => {
let image=req.files.fieldName

})


image.mv('./public/images/foldername/'   'imageName'   '.jpg', (err) => {
  if (err) {

console.log(err)

  } else {

res.redirect('/)



}})

once it is done when you submit your form you can see the uploaded image in your server /public/images/foldername .

  • Related