制作一個帶有管理部分的基本博客,以學習 node 和 express 的基礎知識。我剛剛實作了multer中間件,將博客文章的影像保存到服務器上的檔案夾(“影像”)中 - 而不是 mongo 或 s3 存盤桶 - 現在保持簡單以供學習。
我正在使用EJS和使用res.render來發送和呈現前端。但是,我也想將影像放入 EJS 檔案中。我試過簡單地傳入檔案名,如下所示:
res.render(path.resolve(__dirname, "../", "views", "posts.ejs"), {postData, file});
postData是來自 mongodb 集合的帖子上的資料。所有這些都是發送檔案名本身,這沒有幫助。
我環顧四周,但似乎沒有找到答案,還是我想多了?
這是控制器的其余代碼:
const path = require("path");
const fs = require('fs');
const Post = require('../models/modelPosts');
exports.getPost = (req, res, next) => {
const postPath = req.params.post;
Post.findOne({ postPath: postPath }, (error, postData) => {
if (error) { return next(error) };
if (postData.postReadyToView == true) {
// find the correct image
fs.readdirSync('./images').forEach(file => {
const stringOfFile = JSON.stringify(file);
const stringOfPathJPEG = JSON.stringify(postPath ".jpeg");
const stringOfPathJPG = JSON.stringify(postPath ".jpg");
const stringOfPathPNG = JSON.stringify(postPath ".png")
// send the ejs file and image
if (stringOfFile == stringOfPathJPEG ||
stringOfFile == stringOfPathJPG ||
stringOfFile == stringOfPathPNG) {
res.render(path.resolve(__dirname, "../", "views", "posts.ejs"), {
postData, file
});
}
})
} else {
res.redirect(404, "/404");
}
})
};
uj5u.com熱心網友回復:
將要渲染的頁面的檔案路徑作為資料發送,在nodejs中使用express.static將image Garden檔案夾(例如:public/images)注冊為靜態檔案夾,在渲染頁面加載檔案路徑時加載圖片. 我想你可以。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/364405.html
