Skip to content
Advertisement

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

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

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement