我已成功存储上传图片的图片路径。它们看起来像http://localhost/public/Images/okro.jpg
但我不知道如何从数据库中获取它们并在前端显示它们。
有没有办法可以获取所有图像路径并在前端显示它们?
我使用Express框架和Ejs作为我的视图引擎。
修改
请求的server.js代码。
var express = require("express");
var app = express ();
var port = process.env.PORT || 5000;
var bodyParser= require('body-parser');
var mongoose = require('mongoose');
var schema = mongoose.Schema;
var passport = require('passport');
var expressValidator = require('express-validator');
var flash = require('connect-flash');
var session = require('express-session');
var cookieParser = require('cookie-parser');
var morgan = require('morgan');
var configDB = require('./config/db.js');
var multer = require('multer');
var crypt = require('crypto');
var static = require('express-static');
//var upload = multer({ dest: 'public/Images/' })
//connect to mlab database
mongoose.connect(configDB.url);
// log every request to the console
app.use(morgan('combined'));
//read cookies (needed for auth)
app.use(cookieParser());
// get information from html forms
app.use(bodyParser());
//required for passport
app.use(session({ secret: 'ilovescotchscotchyscotchscotch' }));
app.use(passport.initialize());
// persistent login sessions
app.use(passport.session());
//connect-flash for displaying messages.
app.use(flash());
// load our routes.
require('./config/router.js')(app, passport);
require('./config/passport.js')(passport);
require('./config/upload.js')(app, crypt);
//upload meme
//require ('./config/upload.js');
// set up ejs for templating
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(static(__dirname));
app.use(static(__dirname + 'Images'));
//app.use(static(__dirname + '/public'));
//app.use(static('/public'))
//app.use('public/Images', express.static('public'))
//app.use(express.directory(__dirname + '/public'));
//setting up multer
//app.use(multer());
//launch the app
app.listen(port);
console.log('The magic happens on port ' + port);
答案 0 :(得分:1)
您好像使用Images
作为静态文件夹。所以你只需要mongoDB中图片的名称。
例如:
"meme": {
"imgs": "meme.jpg"
}
在你的路线中:
app.get('/', function (req, result) {
const query = Meme.findOne({});
query.select('meme');
query.exec(function (err, meme) {
if (err) return handleError(err);
result.render('/index', {
path: meme.meme.imgs
});
}
}
在.ejs文件中,您将使用:
<img src=<%= path %> alt="image">