Node.js+EJS博客更新模块异常:未编辑图片丢失问题求助
解决Node.js+EJS博客更新文章时原有图片丢失的问题
我用Node.js和EJS搭建了博客,更新文章时遇到问题:文本内容能正常更新,但哪怕没编辑图片,原有图片也会丢失。我试过调整图片路径、调试和控制台检查,以下是我的编辑与更新模块代码以及对应的EJS视图:
编辑与更新模块代码
//Modulo para editar un post app.get("/edit/:id", (req, res) => { const postId = req.params.id; db.query("SELECT * FROM posts WHERE id = ?", [postId], (err, results) => { if (err) throw err; res.render("edit", { post: results[0] }); }); }); //Modulo de actualización app.post("/update/:id", upload.single('image'), (req, res) => { const postId = req.params.id; const { title, content } = req.body; const imagePath = req.file ? req.file.filename : null; console.log(req.file); // Verifica si hay un archivo cargado console.log(imagePath); // Verifica la ruta de la imagen db.query( "UPDATE posts SET title = ?, content = ?, image_path = ? WHERE id = ?", [title, content, imagePath, postId], (err, results) => { if (err) throw err; res.redirect("/index"); } ); });
对应的EJS视图代码
<form class="blog" action="/update/<%= post.id %>" method="POST" enctype="multipart/form-data"> <input type="text" name="title" value="<%= post.title %>" required /> <input type="file" name="image" accept="image/*" /> <input type="text" name="content" value="<%= post.content %>" required /> <button type="submit">Actualizar cambios</button> </form>
问题原因
核心问题出在更新逻辑里:当用户没有选择新图片时,req.file为undefined,你把imagePath设成了null,执行UPDATE语句时会直接把数据库里的image_path字段覆盖为null,导致原有图片的路径丢失。
修复方案
1. 修改更新路由,保留原有图片路径
在执行更新操作前,先查询该文章当前的图片路径,当没有上传新图片时,使用原有路径而非null。修改后的更新代码如下:
//Modulo de actualización app.post("/update/:id", upload.single('image'), (req, res) => { const postId = req.params.id; const { title, content } = req.body; // 先查询数据库中当前文章的原有图片路径 db.query("SELECT image_path FROM posts WHERE id = ?", [postId], (err, results) => { if (err) throw err; const originalImagePath = results[0].image_path; // 有新图片则用新路径,无新图片则保留原路径 const imagePath = req.file ? req.file.filename : originalImagePath; console.log(req.file); // 检查是否有新文件上传 console.log(imagePath); // 确认最终使用的图片路径 db.query( "UPDATE posts SET title = ?, content = ?, image_path = ? WHERE id = ?", [title, content, imagePath, postId], (err, results) => { if (err) throw err; res.redirect("/index"); } ); }); });
2. 优化EJS视图(可选,提升用户体验)
在编辑页面显示当前文章的图片,让用户直观看到现有图片,避免误操作:
<form class="blog" action="/update/<%= post.id %>" method="POST" enctype="multipart/form-data"> <input type="text" name="title" value="<%= post.title %>" required /> <!-- 显示当前已有的图片 --> <% if (post.image_path) { %> <div class="current-image-preview"> <p>当前图片:</p> <img src="/uploads/<%= post.image_path %>" alt="文章当前图片" style="max-width: 200px; margin: 10px 0;"/> </div> <% } %> <input type="file" name="image" accept="image/*" /> <input type="text" name="content" value="<%= post.content %>" required /> <button type="submit">Actualizar cambios</button> </form>
(注意:/uploads/需替换为你项目中存放上传图片的静态资源路径)
内容的提问来源于stack exchange,提问作者Juan Flores
相关产品推荐
相关产品推荐

