微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何将 Multer 与 Express.static("public") 和 EJS 一起用作视图引擎?

如何解决如何将 Multer 与 Express.static("public") 和 EJS 一起用作视图引擎?

我在 Express 和 EJS 中使用 multer。我正在将 multer 返回的文件路径保存到我的数据库中,以进一步将路径传递给 ejs 模板。但是文件路径包括“public”文件夹,因为我已将认视图引擎设置为 ejs 和 express.static("public")。由于文件路径,当在图像中的 ejs 模板中传递时,multer 返回的存储在我的数据库中的路径不可见。有没有办法让我的图像正确显示?这是我的代码

我的文件结构:

  1. 公开>上传

    视图>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");
    }

});

存储在我的数据库中的数据:

enter image description here

解决方法

像这样删除 public/ 前缀字符串:

let filePath = 'public\upload\profile_1609301637277.PNG'
filePath = filePath.split('/').slice(1).join('/')
console.log(filePath) //=> upload/profile_1609301637277.PNG

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。