0

i can now upload images to my server. Now i want to display the same image in a div container automatically.

i dont wanna use this <img src= "image.png">

how i can realize that? I have to use only node and javascript

this is my code for upload and it works

 server.use(upload())
   server.get('/', (req, res) =>{
res.sendFile(__dirname + '/home.html')
})

server.post('/', (req,res)=>{
  if(req.files){
    console.log(req.files)
     var file = req.files.file
     var filename = file.name
    console.log(filename)

     file.mv('./upload/' + filename, function(err){
      if(err){
      res.send(err)
      }else{
      res.send("File Uploaded")
  }
})
}
});

this is my html where i want my image

<div class="wrapper">
    <h2><legend>Your image here</h2>
</div>
Büsra D
  • 27
  • 6
  • You don't need PHP for uploading images, PHP is just a language you can use for your server side code. The image preview is answered [here](https://stackoverflow.com/questions/4459379/preview-an-image-before-it-is-uploaded) and the image upload is answered [here](https://stackoverflow.com/questions/42578284/multer-image-upload-in-nodejs-and-express) I think [this tutoria](https://code.tutsplus.com/tutorials/file-upload-with-multer-in-node--cms-32088) covers everything you need. – huichops May 31 '20 at 16:36

1 Answers1

1

Okay, I recommend using the <img/> tag as it's better for accessibility and it's just good practice. I know when I started, all I would use were divs for images because they look the best. However, there is a better way. This link should give you all you need to know on how to make an img tag work well with a div: https://css-tricks.com/almanac/properties/o/object-fit/ - And the code is:

div{
  object-fit: cover; /* Change to whatever styling you need */
}

<div class="wrapper">
  <h2><legend>Your image here</h2>
  <img src="image.png" alt="Describe your image">
</div>

However, should this really not be the approach you're looking for, you can apply the image to a background-image in the styling of the div using the 'url' attribute. For example:

div{
  background-image: url('/path/to/img');
}
<div class="wrapper">
    <h2><legend>Your image here</h2>
</div>

This can be done using inline-styles, also:

<div class="wrapper" style="background-image: url('/path/to/img');">
    <h2><legend>Your image here</h2>
</div>

You'll probably want some further styling for the background image to achieve the look you want. This link: https://www.w3schools.com/cssref/pr_background-image.asp should cover most of the subject. Main things to look at are:

  • background-repeat,
  • background-size, and
  • background-position