如何使用NodeJS上传图像并表达?

时间:2016-05-02 18:08:57

标签: node.js pug

我想将图片上传到指定的文件夹,并使用 mongoose multer 模块。

我添加了var mongoose = require('mongoose'); var passport = require('passport'); var Project = require('../models/projects'); var multer = require('multer'); var ImageSavePath = multer({ dest: '../userFiles/projectImage', rename: function (fieldname, filename) { return filename.replace(/\W+/g, '-').toLowerCase() + Date.now(); }); } module.exports = { plain : function (req, res) { //Datos cocinados con la respuesta... if(!req.user){ res.redirect('/user/login'); } res.render('project/resume', { // resume page view parameters title : "proyectos", user : req.user, }); }, create : function (req, res) { //Datos cocinados con la respuesta... if(!req.user){ res.redirect('/user/login'); } res.render('project/create', { // resume page view parameters title : "Crear proyecto", user : req.user, projectName: "Nombre del proyecto", image: "Subir imágen", plane: "Subir plano en formato PDF", details: "Detalles, información sobre el proyecto.", ammount: "¿Cual es el coste de esto?", location: "Localización", }); }, saveProject : function (req, res){ ImageSavePath.array(req.body.image[5]); var saveProject = new Project({ ProjectOwner : req.user._id, ProjectName : req.body.projectName, ProjectDetails : req.body.projectDetails ProjectImagePath : ImageSavePath, ProjectPdfPath : req.body.plane, ProjectAmount : req.body.ammount, ProjectLocation : req.body.localize, }); saveProject.save(function(err){ if(err){ res.render('project/create', { title: "La información no es válida, volver a introducir los datos", }); } }); }, } 如何在var mongoose = require('mongoose'); var Schema = mongoose.Schema; var project = new Schema({ ProjectOwner: String, ProjectName: String, ProjectDetails: String, ProjectImagePath: [String], ProjectPdfPath: String, ProjectLocation: Number, ProjectAmount: String, }); module.exports = mongoose.model('project', project); 内将文件路径作为字符串?这是我的文件:

控制器/ projectController.js

var express = require('express');
var controller = require('../controllers/projectController');
var passport = require('passport');
var router = express.Router();


router.get('/', controller.plain);
router.get('/create', controller.create);
router.post('/create', controller.saveProject);
//router.get('/edit', controller.create);
//router.post('/create', controller.save);
//router.get('/delete', controller.delete);
module.exports = router;

模型/ projects.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var session = require('express-session');

var index = require('./routes/index');
var users = require('./routes/users');
var projects = require('./routes/projects');

var app = express();
// para devolver estado por consola.
app.use(morgan('combined'));
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
var Account = require('./models/accounts');
passport.use(new LocalStrategy(Account.authenticate()));
passport.serializeUser(Account.serializeUser());
passport.deserializeUser(Account.deserializeUser());

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

app.use(express.static(path.join(__dirname, 'public')));

app.use(require('express-session')({
    secret: 'topSecret',
    resave: true,
    saveUninitialized: true,
    cookie: { maxAge : 3600000 } //1 Hour
}));

app.use(passport.initialize());
app.use(passport.session());
//Rutas express
app.use('/', index);
app.use('/user', users);
app.use('/project', projects);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

mongoose.connect('mongodb://localhost/database');

module.exports = app;

路由/ projects.js

extends ../includes/layout

block content
  div(class="wrap")
    include ../includes/header
    div(class="column-group vertical-space")
      div(class="all-50 push-center")
        div(class="all-100")
          h1 #{title}
        div(class="all-100")
        form(role="form" method="post" action="create" enctype="multipart/form-data")
          p #{projectName}
          input(type="text" name="projectName" required)
          p #{image}
          input(type="file" name="image")
          p #{plane}
          input(type="file" name="plane")
          p #{details}
          input(type="text" name="details")
          p #{ammount}
          input(type="number" name="ammount")
          p #{location}
          input(type="text" name="localize")
          button(type="submit") Enviar
    div(class="push")
  include ../includes/footer

app.js

{{1}}

项目/ create.jade

{{1}}

2 个答案:

答案 0 :(得分:0)

部分解决

在create.jade模板中使用enctype="multipart/form-data"形式的是一个问题,如果没有这个,我可以将字段信息添加到req.body属性,例如req。 body.projectName,req.body.planereq.body.details ...我需要解决enctype发生的事情,并将文件保存在数据库中保存的路径中。

答案 1 :(得分:0)

<强>解决!

最后,我必须在 routes / projects.js 文件上更改上面的 multer ,并在上将req.file.path属性添加到ProjectImagePath > controllers / projectController.js 文件。

代码如下:

<强>路由/ projects.js

var express = require('express');
var controller = require('../controllers/projectController');
var passport = require('passport');
var multer = require('multer');
var router = express.Router();
var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, '../userFiles/projectImage')
  },
  filename: function (req, file, cb) {
    cb(null, "UploadedOn" + Date.now() + "fileOrigName" + file.originalname)
  }
})
var upload = multer({ storage: storage});


router.get('/', controller.plain);
router.get('/create', controller.create);
router.post('/create', upload.single('image'), controller.saveProject);
//router.get('/edit', controller.create);
//router.post('/create', controller.save);
//router.get('/delete', controller.delete);
module.exports = router;

controllers / projectController.js 代码

saveProject : function (req, res, file){
      var savingProject = new Project({
        ProjectOwner : req.user._id,
        ProjectName : req.body.projectName,
        ProjectDetails : req.body.details,
        ProjectImagePath : req.file.path,
        //ProjectPdfPath : .plane,
        ProjectAmount : req.body.ammount,
        ProjectLocation : req.body.localize,
      });
        console.log("***start viewing content from req.body***");
        console.log(req.body);
        console.log("***start viewing content from req.file***");
        console.log(req.file);
        console.log("***start viewing content from savingProject variable***");
        console.log(savingProject);
      savingProject.save(function(err){
        if(err){
          console.log(err);
          res.render('project/create', {
            title: "La información no es válida, volver a introducir los datos",
          });
        }
        if(!err){res.send('ok');}
      });
    },

console.log

***start viewing content from req.body***
{ projectName: 'testingproj',
  details: 'dwada',
  ammount: '111111111',
  localize: 'dwada' }
***start viewing content from req.file***
{ fieldname: 'image',
  originalname: '13062537_587472701434355_1300164321309994729_n.jpg',
  encoding: '7bit',
  mimetype: 'image/jpeg',
  destination: '../userFiles/projectImage',
  filename: 'UploadedOn1462292710895fileOrigName13062537_587472701434355_1300164321309994729_n.jpg',
  path: '../userFiles/projectImage/UploadedOn1462292710895fileOrigName13062537_587472701434355_1300164321309994729_n.jpg',
  size: 88911 }
***start viewing content from savingProject variable***
{ _id: 5728d0e6552274ac2286a84c,
  ProjectLocation: 'dwada',
  ProjectAmount: 111111111,
  ProjectImagePath: '../userFiles/projectImage/UploadedOn1462292710895fileOrigName13062537_587472701434355_1300164321309994729_n.jpg',
  ProjectDetails: 'dwada',
  ProjectName: 'testingproj',
  ProjectOwner: '5720977ffe0697f51001c9a1' }