How can I transfer an image from html to nodejs to use it with ejs?

Issue

I was trying to create a new website using nodejs and expressjs. Basically I have a page (/ home) where there is a form with an input file. I have already created the code to show the preview of the image once loaded … what I would like to do is essentially transfer the "link" of the image to nodejs, where I will then take this "link" and insert it in the src of the img tag in the EJS end. can someone help me? thanks

Solution

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
}))

To save the image here i am storing the image in server itself but this is not recommended .
You want to rename the image with a connection . for eg the mongo document inserted id

image.mv('./public/images/foldername/' + id + '.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 .

To view in ejs you can basically loop through the mongo id or some connection that i have mentioned earlier

Answered By – Naveen Ravi

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published