我首先无法正确地将文件保存到数据库,但在此网站的帮助下,我能够解决这个问题。但我现在的问题是当我尝试在我的一个观点中使用它时,我一直得到一个奇怪的404错误的奇怪路径:
无法获得: http://localhost:3090/project/%7B%20contentType:%20'图像/ PNG',%20%20data:%... B%2047%2044%2000%20FF%2000%20FF%2000%20FF%20a0%20bd%20A7%20 .. %20%3E%20%7D 404(未找到)
这让我觉得它没有在数据库中正确保存,但在Robomongo中,它看起来像这样,这对我来说似乎是正确的:
所以,我可以看到它在URL中有我的内容类型,这显然是一个错误,但我无法弄清楚如何解决这个问题。
我之前在该文件中添加了一些未保存到数据库的图像,并且这些图像使用相同的模板显示正常,因此路径应该是正确的。
非常感谢大家提前!!
我的Index.JS文件:
const express = require('express');
const http = require('http');
const bodyParser = require('body-parser');
const morgan = require('morgan');
const mongoose = require('mongoose');
const path = require('path');
mongoose.Promise = global.Promise;
const router = require('./router');
//App Setup
const app = express();
app.set("view engine", "ejs");
app.use(express.static(path.join(__dirname, 'public')));
app.use(morgan('combined'));
app.use(bodyParser.urlencoded({extended:true}));
router(app);
//DB Setup
mongoose.connect('mongodb://localhost/projectsApp');
mongoose.connection.on('open', () => {
console.log('Connected to mongodb server.');
mongoose.connection.db.listCollections().toArray(function (err, names) {
if(err) {
console.log(err);
} else {
console.log(names);
}
});
})
//Server Setup
const port = process.env.PORT || 3090;
const server = http.createServer(app);
server.listen(port);
router.js文件:
const Project = require('./models/project');
const multer = require('multer');
const fs = require('fs');
const path = require('path');
var upload = multer({ dest: './public/img' })
module.exports = function(app) {
app.get('/admin', (req, res) => {
Project.find({}, (err, projects) => {
if(err) {
console.log(err);
} else {
res.render('admin', {projects: projects});
}
})
});
app.post('/admin', upload.single('image'), (req, res) => {
console.log(req.file);
newProj = {
title: req.body.title,
tech: req.body.tech,
url: req.body.url,
shortDescription: req.body.shortDescription,
longDescription: req.body.longDescription,
image: { data: fs.readFileSync(req.file.path), contentType: 'image/png' }
};
Project.create(newProj, (err, proj) => {
if(err){
console.log(err);
} else {
console.log(proj);
res.redirect("/");
}
});
});
}
最后,视图,以防万一:
<% include ./partials/header%>
<div class="container">
<div class="row">
<div class="col-sm-6">
<div class="project-div">
<h1><%= project.title%></h1>
</div>
</div>
<div class="col-sm-6">
<img src='<%= project.image%>'/>
<hr />
<span><strong>URL: </strong> <a href="<%= project.url%>"><%= project.url%></a></span>
</div>
</div>
</div>
<% include ./partials/footer%>
答案 0 :(得分:0)
您正在尝试直接在模板中输出保存图像数据的对象。这不会起作用,因为这根本不是html如何工作......
我建议为图像设置另一条路线,然后参考该图像。
app.get('/admin/projects/:id/image', (req, res, next) => {
Project.find({ _id: req.params.id }, (err, result) => {
if (err) return next(err)
if (result.length === 0) return next()
res.set('Content-Type', result[0].contentType)
res.send(result[0].data)
})
})
然后在模板中使用该网址:
...
<img src="/admin/projects/<%= project._id %>/image" />
...