2017-09-14 60 views
0

我已经在使用busboy的本地目录上传的图片,并通过 使用猫鼬形象,MongoDB的路径,但现在我无法 检索路径 显示检索图像的路径在我的ejs视图中的图像。我是这个nodejs的新手。请帮我 显示图像。如何从MongoDB中使用的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 %>' > 
+0

我不太明白你的问题。您必须在要显示图像的路径中使用Mongoose检索'path'值。因此,例如'compileSchema.find({“你的键值”},(犯错,结果)=> {//传递给你的respoonse})' – forJ

+0

@serendipity我改变你每建议,但我没有得到返回值,我改变了上面的代码。对不起,打扰您。请帮帮我。谢谢 –

+0

@serendipity我得到了结果非常感谢!但是如何在ejs中显示它。它不显示:( –

回答

1

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

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第一(创建一个架构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'>参考注释。