试图上传图片mongodb(mlab)

时间:2018-02-24 15:11:29

标签: javascript node.js mongodb ejs multer

我正在尝试使用节点js将图像上传到服务器以及本地文件夹。但问题是,当我尝试使用enctype发布表单时,图像只保存在本地文件夹中,而不是在mongodb中。但是如果我删除enctype,那么图片只会保存在mongodb中。



<form  method="POST" enctype="multipart/form-data" action="/posts" >
&#13;
&#13;
&#13;

我的server.js文件---

&#13;
&#13;
//call module
var express = require('express');
var app = express();
var path = require('path')
var multer = require('multer')
//var upload = multer({dest: './uploads'})
var routes = require('./routes/index')
const bodyParser= require('body-parser')
//var port = process.env.PORT|| 3000;

// Multer path define
var storage = multer.diskStorage({
	destination: './uploads',
	filename: function(req,file,cb){
		cb(null,file.fieldname + '_' + Date.now() +path.extname(file.originalname) );
	}
});
// init upload

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


app.use(bodyParser.urlencoded({extended: true}))

app.set('view engine','ejs');

//connect Mongodb
const MongoClient = require('mongodb').MongoClient
var db
MongoClient.connect('mongodb://admin:test@ds147118.mlab.com:47118/neelcrud', (err, client) => {
  if (err) return console.log(err)
  db = client.db('neelcrud') // whatever your database name is
  app.listen(3000, () => {
    console.log('listening on 3000')
  })
})

//routes
app.get('/', (req,res)=>{
	res.render('index')
})
app.post('/posts',  upload.single('post_iamge'), (req,res)=>{
	
	  db.collection('posts').save(req.body, (err, result) => {
    if (err) return console.log(err)

    console.log('saved to database')
	console.log(req.body)
	//console.log(req.file)
    res.render('index.ejs')
  })
	  
})

app.get('/blog',(req,res)=>{
	  db.collection('posts').find().toArray((err, result) => {
    if (err) return console.log(err)
    // renders index.ejs
    res.render('blog',{posts: result})
  })
})
&#13;
&#13;
&#13;

我的index.ejs文件---

&#13;
&#13;
<html>
<head>

  <title>MY APP</title>
</head>
<body>
  May Node and Express be with you.
  <form  method="POST" enctype="multipart/form-data" action="/posts" >
    <input type="text" placeholder="post" name="post_title">
    <!-- <input type="file" name="post_iamge"> -->
    <input type="file" name="post_iamge" accept=""/>
    <input type="text" placeholder="comment" name="post_comment">
    <button type="submit">Submit</button>
  </form>
</body>
</html>
&#13;
&#13;
&#13;

0 个答案:

没有答案