'how to retain the value of an uploaded image when i click on the edit post?
I am using Express, Mongodb for backend and multer library for storing the uploaded images. and ejs as template engine. I could successfully uploaded the Images, view the uploaded images and delete them. But the problem comes when I tried to edit the post which consist of 3 text fields and an images. when I click on the edit button i could able to set the value of the input fields of the post which I am editing but it is not same case for the image which i have uploaded. I need some help.
edit.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<%- include('../partials/head'); %>
</head>
<body class="container">
<header>
<%- include('../partials/header') %>
</header>
<main>
<div class="jumbotron">
<form method="post" action="/edit/<%=image._id%>?_method=put" enctype="multipart/form-data">
<div class="mb-3">
<label for="" class="form-label">Title</label>
<input type="text" class="form-control" name="title" value="<%= image.title %>">
</div>
<div class="mb-3">
<label for="" class="form-label">heading</label>
<input type="text" class="form-control" name="heading" value="<%= image.heading %>">
</div>
<div class="mb-3">
<label for="" class="form-label">content</label>
<input type="text" class="form-control" name="content" value="<%= image.content %>">
</div>
<div class="mb-3">
<label for="" class="form-label">upload</label>
<input type="file" class="form-control" name="myImage" value="<%= image.imageUrl %>">
</div>
<button type="submit" class="btn btn-primary">update</button>
</form>
</div>
</main>
<footer>
<%- include('../partials/footer') %>
</footer>
</body>
</html>
edit routes
app.get('/edit/:id', async(req, res) => {
const image = await Image.findById(req.params.id);
if (image)
res.render('pages/edit', { image: image })
})
//edit image
app.put("/edit/:id", upload.single('myImage'), (req, res, next) => {
// console.log(req.file);
const cimage = Image.findById(req.params.id);
// console.log(cimage.obj);
cimage.updateOne({
title: req.body.title,
content: req.body.content,
heading: req.body.heading,
imageUrl: req.file.path
})
.then(result => {
res.redirect('/images')
})
})
gets redirected to edit page when clicked on the edit button of images.ejs
<main>
<div class="jumbotron container">
<ul class="row">
<% images.map((image)=>{%>
<li class="col">
<p>
<%=image.title %>
</p>
<p>
<%=image.content %>
</p>
<p>
<%=image.heading %>
</p>
<img width="600" height="400" src="<%= image.imageUrl %>" alt="">
<form method="POST" action="/delete/<%= image._id %>?_method=delete">
<button class="btn btn-primary" type="submit" onClick="return confirm('Are you sure you want to delete?')">delete</button>
</form>
<a class="btn btn-primary" href="/edit/<%= image._id %>">edit</a>
</li>
<% })%>
</ul>
</div>
</main>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
