问题描述
我在 Express 和 EJS 中使用 multer。我正在将 multer 返回的文件路径保存到我的数据库中,以进一步将路径传递给 ejs 模板。但是文件路径包括“public”文件夹,因为我已将默认视图引擎设置为 ejs 和 express.static("public")。由于文件路径,当在图像中的 ejs 模板中传递时,multer 返回的存储在我的数据库中的路径不可见。有没有办法让我的图像正确显示?这是我的代码:
我的文件结构:
-
公开>上传
视图>main.ejs
我的 app.js 文件
// 节点应用配置
const app = express();
app.use(express.static("public"));
app.set("view engine","ejs");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// 存储引擎
const storage = multer.diskStorage({
destination: './public/upload',filename: (req,file,cb) => {
return cb(null,`${file.fieldname}_${Date.Now()}${path.extname(file.originalname)}`)
}
})
const upload = multer({
storage: storage,limits:{
fileSize: 10485760
}
})
app.use('/profile',express.static('upload'));
//主要获取方法
app.get("/main",function (req,res) {
if (req.isAuthenticated()) {
User.find({ "secret": { $ne: null },"filePath": { $ne: null }},function(err,foundUser,filePath){
if(err){
console.log(err);
}else{
if(foundUser ){
res.render("main",{
usersWithSecrets: foundUser,usersWithImages: filePath
});
console.log(foundUser);
}
}
}
);
} else {
res.redirect("/login");
}
});
存储在我的数据库中的数据:
解决方法
像这样删除 public/
前缀字符串:
let filePath = 'public\upload\profile_1609301637277.PNG'
filePath = filePath.split('/').slice(1).join('/')
console.log(filePath) //=> upload/profile_1609301637277.PNG