使用NodeJS显示图像文件

时间:2018-07-17 17:18:30

标签: node.js mongodb

使用node.js和mongodb,我要上传图像并使用其ID显示该图像。

但是当我运行它时,显示错误。

错误:无法在视图目录“ H:\ NodeJS \ AddImage”中查找视图“ / showImage” \ views“

进行了很多搜索,但找不到适合我的合适解决方案。

出什么问题了?

任何人都可以帮忙吗?

谢谢..

directories

这是我的代码...........

app.js

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var path = require('path');
var multer = require('multer');
app.use(bodyParser.json());

app.use(express.static('public'));

var imagefile = require('./routes/imagefile');
app.set('view engine', 'ejs');
mongoose.connect('mongodb:..url');

imagefile(app);
app.listen(3000);

console.log('Running on port 3000');

imagefile.js

var express = require('express');
var multer = require('multer');
var mongoose = require('mongoose');
var fs = require('fs');

var imageSchema = mongoose.Schema({
      img: { data: Buffer, contentType: String },
      imageName : String
  });
var Item = mongoose.model('Clothes',imageSchema);

var storage = multer.diskStorage({
 destination: function(req, file, cb) {
 cb(null, 'public/')
 },
 filename: function(req, file, cb) {
 cb(null, file.originalname);
 }
});

var upload = multer({
 storage: storage
});

module.exports = function (app) {

app.get('/', function(req, res, next) {
 res.render('index.ejs');
});

app.get('/images/:id', function(req, res) {

  Item.findById(req.params.id, function (error, result) {
    //res.contentType(result.contentType);
    console.log(result.imageName);
    //res.end(result.image.buffer, "binary");
    res.render('/showImage',{imageName : result.imageName, imageId : result.imageName});
});
});

app.post('/', upload.any(), function(req, res, next) {

   var newItem = new Item();
   newItem.img.data = fs.readFileSync(req.files[0].path)
   newItem.img.contentType = 'image/png';
   newItem.imageName = req.files[0].originalname;
   newItem.save();
   res.render('index.ejs');

});

};

index.ejs

<html>
  <head>
    <title>test</title>
  </head>
  <body>
    <form action "/" method="POST" enctype="multipart/form-data">
      <input type="file" name="myimage" ></input>
      <input type="submit" name="submit" value="submit"></input>
    </form>
  </body>
</html>

showImage.ejs

<html>
  <head>
    <title>test</title>
  </head>
  <body>
    <h1><%= imageName %></h1>
    <h1><%= imageId %></h1>
    <div class="header">
      <img src='/public/36417514_2140268509321308_7450232816341614592_n.jpg %>' />
    </div>
  </body>
</html>

1 个答案:

答案 0 :(得分:1)

删除此功能中的前导斜杠:

app.get('/images/:id', function(req, res) {

   // Rest of the code
   // ...
   res.render('showImage', // <-- Remove slash
     {imageName : result.imageName, imageId : result.imageName});
   });
});

问题在于它正在查找名为“ /showImage.ejs”的文件。