GridFS / multer-无法读取未定义的属性“文件名”

时间:2019-11-11 11:52:31

标签: javascript node.js mongodb express ejs

我不是Web开发方面的杰出专家(至少目前希望如此),所以我的问题可能有点傻。

这是我的问题: 我一直在研究Node.Js,并试图创建一个数据库,我可以在其中上传图片,然后检索它们并通过.ejs文件在浏览器中显示它们。

不幸的是,在app.js文件中,我能够console.log images数组,并检查至少一个文件的filename,同时在.ejs上循环访问这样做:

   `<% for(var i = 0; i <= images.length; i++){ %>
        <img src="<%= images[i].filename %>">
    <% } %>`

我收到此问题标题中所示的错误。

有人知道我在做什么错吗?我相信我使用GridFS或multer设置了错误,但是我不确定100%。

在此先感谢您打算答复的人。

现在您可以在app.js文件中找到我正在使用的代码:

var express                         = require('express'),
    mongoose                        = require('mongoose'),
    bodyParser                      = require('body-parser'),
    methodOverride                  = require('method-override'),
    expressSanitizer                = require('express-sanitizer'),
    path                            = require('path'),
    crypto                          = require('crypto'),
    multer                          = require('multer'),
    GridFsStorage                   = require('multer-gridfs-storage'),
    Grid                            = require('gridfs-stream'),
    app                             = express();

//connect to the MongoDB database
mongoose.connect("mongodb+srv://***:*****@cluster-***-***-q5eof.mongodb.net/*****?retryWrites=true&w=majority", 
{ useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true});

//connect to the MongoDB database
var mongoURI = "mongodb+srv://***:*****@cluster-***-***-q5eof.mongodb.net/*****?retryWrites=true&w=majority";

var conn = mongoose.createConnection(mongoURI)

//parseing incoming request bodies in a middleware before the handlers, available under the req.body property
app.use(bodyParser.urlencoded({extended: true}));

//setting the engine to read directly the ejs files without specifying their extentions on the routes
app.set('view engine', 'ejs');

//serving images, CSS files, and JavaScript files in a directory named public:
app.use(express.static('public'));

//setting method-override to be used via '_method' text before specifying the type of method used in a form
app.use(methodOverride('_method'));

//execute express-sanitizer
app.use(expressSanitizer());

let gfs
conn.once('open', () => {
  gfs = Grid(conn.db, mongoose.mongo)
  gfs.collection('uploads')
  console.log('GRID CONNECTION SUCCESSFUL')
})

//Landing page
app.get('/', function(req, res){
    gfs.files.find().toArray(function(err, images){
        if(err){
            console.log(err)
        } else {
                images.map(function(image){
                image.isImage = true;
            });
        }
        res.render('landing', {images: images});
        console.log(images[0].filename);
    });
});

//Create storage engine
 var storage = new GridFsStorage({
  url: mongoURI,
  file: (req, file) => {
    return new Promise((resolve, reject) => {
      crypto.randomBytes(16, (err, buf) => {
        if (err) {
          return reject(err);
        }
        const filename = buf.toString('hex') + path.extname(file.originalname);
        const fileInfo = {
          filename: filename,
          bucketName: 'uploads'
        };
        resolve(fileInfo);
      });
    });
  }
});
const upload = multer({ storage });

//Upload page
app.get('/upload', function(req, res){
    res.render('upload');
});

//Sending form from upload page
app.post('/upload', upload.array('file'), function(req, res){
    res.json({file: req.files});
});

app.listen('3000', function(err){
    if(err){
        console.log(err)
    } else{
        console.log("APP CONNECTED")
    }
});

1 个答案:

答案 0 :(得分:0)

这将为您服务,示例代码

const multer = require('multer');   //FOR FILE UPLOAD

let storage = multer.diskStorage({ //multers disk storage settings
  destination: function (req, file, cb) {
    cb(null, './public');
  },
  filename: function (req, file, cb) {
    let datetimestamp = Date.now();
    cb(null, file.originalname);
  }
});

let upload = multer({ //multer settings
  storage: storage
}).single('file');


let uploadfile = (req, res, next) => {
  let path = '';
  upload(req, res, function (err) {
    if (err) {
      return res.status(422).send("an Error occured");
    }
    let path = req.file.path;
    req.file = path;
    next();

  });
}