如何使用 Nodejs 从 mongoDB 检索图像路径

How to retrieve path of image from mongoDB using Nodejs

我已经使用 Busboy 将图片上传到本地目录并通过了 MongoDB 使用 Mongoose 的图像路径,但现在我无法 检索路径 在我的 ejs 视图中显示图像。我是这个 nodejs 的新手。请帮我 显示图像。

非常感谢您:)

var express = require('express');    //Express Web Server
var busboy = require('connect-busboy'); //middleware for form/file upload
var path = require('path');     //used for file path
var fs = require('fs-extra');       //File System - for file manipulation
var mongoose = require('mongoose');
var mongoClient = require('mongodb').mongoClient;
var objectId = require('mongodb').ObjectId;
var app = express();
app.use(busboy());
app.use(express.static(path.join(__dirname, 'public')));
mongoose.Promise = global.Promise;

mongoose.connect('mongodb://localhost:27017/postname');
/* ==========================================================
Create a Route (/upload) to handle the Form submission
(handle POST requests to /upload)
Express v4  Route definition
============================================================ */
app.set('view engine','ejs');
 app.use(express.static(__dirname + '/public'));

var nameSchema = mongoose.Schema({
  newfile: Object,
  path: String
});

var compileSchema = mongoose.model('foods', nameSchema);
app.get('/', function(req, res, next) {
  res.render('index',{'title': 'New post app'});
});
app.route('/')
    .post(function (req, res, next) {
        var fstream;
        req.pipe(req.busboy);
        req.busboy.on('file', function (fieldname, file, filename) {
            console.log("Uploading: " + filename);
            //Path where image will be uploaded
            fstream = fs.createWriteStream(__dirname + '/public/uploads/' + filename);
            var dirname = path.join(__dirname + '/public/uploads/' + filename);
            file.pipe(fstream);
            //mongo save
            var paths = new compileSchema({newfile : dirname, passReqToCallback: true});
                paths.save(function(err){
                    if(err)  throw err;
                    compileSchema.find({newfile: dirname}, (err, result) =>{
                      console.log();
                      return result;
                    });
              });
            fstream.on('close', function () {
                console.log("Upload Finished of " + filename);
              //where to go next
              res.redirect('/profile');
            });
        });
    });
    app.get('/profile', (req, res)=>{
      res.render('profile',{photo: req.result});
    });
var server = app.listen(3030, function() {
    console.log('Listening on port %d', server.address().port);
});

我的 Ejs 文件是:

<img src='<%= photo.newfile %>' >

这是使用Mongoose写入和读取Mongodb的典型过程。我没有检查你的流媒体和其他东西是否工作正常,但数据库工作流程会更好。

var express = require('express');    //Express Web Server
var busboy = require('connect-busboy'); //middleware for form/file upload
var path = require('path');     //used for file path
var fs = require('fs-extra');       //File System - for file manipulation
var mongoose = require('mongoose');
var mongoClient = require('mongodb').mongoClient;
var objectId = require('mongodb').ObjectId;
var app = express();
app.use(busboy());
app.use(express.static(path.join(__dirname, 'public')));
mongoose.Promise = global.Promise;

mongoose.connect('mongodb://localhost:27017/postname');
/* ==========================================================
Create a Route (/upload) to handle the Form submission
(handle POST requests to /upload)
Express v4  Route definition
============================================================ */
app.set('view engine','ejs');
app.use(express.static(__dirname + '/public'));

//You can import your schema like this
const Name = require('./name');

var compileSchema = mongoose.model('foods', nameSchema);
app.get('/', function(req, res, next) {
    res.render('index',{'title': 'New post app'});
});

//I have changed your route since it seems to be clashing with the above
app.post('/save' ,function (req, res, next) {
        var fstream;
        req.pipe(req.busboy);
        req.busboy.on('file', function (fieldname, file, filename) {
            console.log("Uploading: " + filename);
            //Path where image will be uploaded
            fstream = fs.createWriteStream(__dirname + '/public/uploads/' + filename);
            file.pipe(fstream);
            var dirname = path.join(__dirname + '/public/uploads/' + filename);
            //mongo save

            fstream.on('close', function () {
                //You can either save to mongodb after streaming closes or while it is streaming but in this case I will do it after.
                console.log("Upload Finished of " + filename);
                //where to go next

                //Declare your schema object here
                let name = new Name({
                    newfile:'Whatever you want to store here',
                    path: path
                });

                //Save your declared schema like this
                name.save((err) => {
                    if(err) throw err;

                    console.log(`saved : ${name}`);

                    //When you redirect here, it will go to /profile route
                    res.redirect('/profile');
                });
            });
        });
    });
app.get('/profile', (req, res)=>{

    //You must retrieve from mongodb your object here if this is where you want the object to be

    //{} empty query will find all objects in the table
    Name.find({}, (err, result) => {
        if(err) throw err;
        //after everything was found, send it to front end

        res.render('profile',{
            photo: req.result,
            //Now your 'compileSchema' object is available at front end as 'result' object
            result:result
        });
    });
});

var server = app.listen(3030, function() {
    console.log('Listening on port %d', server.address().port);
});

name.js(为您将使用的每个 table 创建一个模式 js 文件)

let mongoose = require('mongoose');
let Schema = mongoose.Schema;

let compileSchema = new Schema({
    newfile: Object,
    path: String
});

let Compile = mongoose.model('Compiles', compileSchema);

module.exports = Compile;

首先检查您是否正确接收和传输文件。如果你是,它必须工作正常。另外,我不知道你为什么要保存 newfile:object 字段,但你真正需要做的就是保存图像文件的路径,然后在需要使用图像的地方检索它,并将路径用作<img src='path'>参考评论